Android 压缩图像时的OOM?
当使用以下代码压缩图像时,我得到OOM。我在写入文件后回收了位图。但是当压缩大图像或连续重复三到四次时,应用程序会因OOM错误而崩溃。有人能帮我摆脱这个问题吗Android 压缩图像时的OOM?,android,bitmap,out-of-memory,image-compression,Android,Bitmap,Out Of Memory,Image Compression,当使用以下代码压缩图像时,我得到OOM。我在写入文件后回收了位图。但是当压缩大图像或连续重复三到四次时,应用程序会因OOM错误而崩溃。有人能帮我摆脱这个问题吗 /** * A simple class that compresses images from resources given */ public class ImageCompressor { public static String compressImage(final Context context, final
/**
* A simple class that compresses images from resources given
*/
public class ImageCompressor {
public static String compressImage(final Context context, final String filePath) {
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
options.inPurgeable = true;
options.inInputShareable = true;
}
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out;
String filename = getFilename(context);
try {
out = new FileOutputStream(filename);
// write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
if (bmp != null && !bmp.isRecycled())
bmp.recycle();
if (scaledBitmap != null && !scaledBitmap.isRecycled())
scaledBitmap.recycle();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
private static String getFilename(final Context context) {
return (Util.getCompressedPicPath(context).getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
}
/**
* Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
* the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap
* having a width and height equal to or larger than the requested width and height.
*
* @param options An options object with out* params already populated (run through a decode*
* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
/**
*压缩来自给定资源的图像的简单类
*/
公共级图像压缩程序{
公共静态字符串压缩图像(最终上下文,最终字符串文件路径){
位图缩放位图=空;
BitmapFactory.Options=new-BitmapFactory.Options();
//通过将此字段设置为true,实际位图像素不会加载到内存中。只加载边界。如果
//如果您尝试在此处使用位图,将得到null。
options.inJustDecodeBounds=true;
位图bmp=BitmapFactory.decodeFile(文件路径,选项);
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
//压缩图像的最大高度和宽度值为816x612
浮动最大高度=816.0f;
浮动最大宽度=612.0f;
浮动高度=实际宽度/实际高度;
浮点最大比值=最大宽度/最大高度;
//设置宽度和高度值以保持图像的纵横比
如果(实际高度>最大高度| |实际宽度>最大宽度){
if(imgRatiomaxRatio){
imgRatio=最大宽度/实际宽度;
实际高度=(int)(imgRatio*实际高度);
实际宽度=(int)最大宽度;
}否则{
实际高度=(int)最大高度;
实际宽度=(int)最大宽度;
}
}
//设置inSampleSize值允许加载原始图像的缩小版本
options.inSampleSize=calculateInSampleSize(选项、实际宽度、实际高度);
//inJustDecodeBounds设置为false以加载实际位图
options.inJustDecodeBounds=false;
//此选项允许android在内存不足时声明位图内存
if(Build.VERSION.SDK\u INT