public Bitmap getBitmap(byte[] bytes) { Options opt = new Options(); opt.inJustDecodeBounds = true; //只分配边界不分配像素DecodeBitmap时候 decodeBitmap(bytes, opt); if (opt.outHeight * opt.outWidth < MAX_IMAGE_PIXELS) { return decodeBitmap(bytes, null); } return null; } public byte[] getBytes(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } public Bitmap resizeImage(byte[] original, int maxWidth, int maxHeight, boolean stretch) { Options opt = new Options(); opt.inJustDecodeBounds = true; decodeBitmap(original, opt); int width = opt.outWidth; int height = opt.outHeight; // Scale the bitmap as we're decoding it to avoid out of memory errors. opt.inJustDecodeBounds = false; if (width > maxWidth && height > maxHeight) { opt.inSampleSize = Math.min(width / maxWidth, height / maxHeight); } else if (width > maxWidth) { opt.inSampleSize = width / maxWidth; } else if (height > maxHeight) { opt.inSampleSize = height / maxHeight; } int powerOfTwo = 1; while (powerOfTwo * 2 < opt.inSampleSize) { powerOfTwo *= 2; } // According to docs, powers of two are more efficient and more accurate. opt.inSampleSize = powerOfTwo; Bitmap scaled = decodeBitmap(original, opt); if (scaled != null) { width = scaled.getWidth(); height = scaled.getHeight(); float scaleWidth = ((float)maxWidth) / width; float scaleHeight = ((float)maxHeight) / height; if (!stretch) { if ((scaleWidth * height) > maxHeight) { scaleWidth = scaleHeight; } else { scaleHeight = scaleWidth; } } Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true); //缩放图像 } return null; } private Bitmap decodeBitmap(byte[] bytes, Options opt) { Bitmap retval = null; if (bytes != null) { try { retval = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt); } catch (OutOfMemoryError oome) { Log.e(ImageHelper.class.getName(), "Out of memory, trying GC...", oome); System.gc(); } catch (Exception e) { Log.e(ImageHelper.class.getName(), "Error decoding bitmap",e); } } return retval; }