@Override public Response<Bitmap> parseNetworkResponse(NetworkResponse response) { synchronized (sDecodeLock) { try { return doParse(response); } catch (OutOfMemoryError e) { KJLoger.debug("Caught OOM for %d byte image, url=%s", response.data.length, getUrl()); return Response.error(new KJHttpException(e)); } } }
/** * 关于本函数的详细解释,可以看我的博客: http://blog.kymjs.com/kjframeforandroid/2014/12/05/02/ * * @param response * @return */ private Response<Bitmap> doParse(NetworkResponse response) { byte[] data = response.data; BitmapFactory.Options option = new BitmapFactory.Options(); Bitmap bitmap = null; if (mMaxWidth <= 0 && mMaxHeight <= 0) { bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, option); } else { option.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, option); int actualWidth = option.outWidth; int actualHeight = option.outHeight; // 计算出图片应该显示的宽高 int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight); int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth); option.inJustDecodeBounds = false; option.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight); Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, option); // 做缩放 if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) { bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true); tempBitmap.recycle(); } else { bitmap = tempBitmap; } } if (bitmap == null) { return Response.error(new KJHttpException(response)); } else { Response<Bitmap> b = Response.success( bitmap, response.headers, HttpHeaderParser.parseCacheHeaders(mConfig, response)); return b; } }