在我的项目中,我需要操作位图并保存它。
为了操纵图像,我应用了一个矩阵,如下所示:
Bitmap b = Bitmap.createBitmap(((BitmapDrawable) imageView.getDrawable()).getBitmap(), 0, 0,width, height, matrix, true);
我这样保存它:
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
问题是,如果这样做,如果位图很大,我可能会收到 OOM 错误。
关于如何避免它的任何建议?
不幸的是,缩小位图不是一个可接受的解决方案,因为我需要保留位图质量。
我也有很多带有位图的OOM,尤其是在较旧的(三星)设备上。可以使用的一种简单方法是捕获 OOM,启动 GC,然后重试。如果再次失败,您可以(例如)向用户显示错误消息。
private void compressBitmap(/* args */) {
Bitmap b = Bitmap.createBitmap(((BitmapDrawable) imageView.getDrawable()).getBitmap(), 0, 0,width, height, matrix, true);
b.compress(Bitmap.CompressFormat.JPEG, 100, out);
}
try {
compressBitmap(/* args */);
} catch(OutOfMemoryError e) {
System.gc();
// try again
try {
compressBitmap(/* args */);
} catch(OutOfMemoryError e) {
System.gc();
// Inform user about the error. It's better than the app crashing
}
}
但是,这只是一种解决方法。如果你真的想在这种情况下有效地防止 OOM,我认为你必须使用 NDK。无论如何,这比应用程序崩溃要好。