Android-对大型相机图像进行下采样时发生OutOfMemoryError
我在从照相机活动中捕获图像、将其保存为较小尺寸以及将保存的图像上载到服务器时遇到间歇性问题 如果图像文件大于特定阈值(我使用2000KB),我将调用以下函数对其进行降采样并保存较小的图像:Android-对大型相机图像进行下采样时发生OutOfMemoryError,android,image,bitmap,out-of-memory,Android,Image,Bitmap,Out Of Memory,我在从照相机活动中捕获图像、将其保存为较小尺寸以及将保存的图像上载到服务器时遇到间歇性问题 如果图像文件大于特定阈值(我使用2000KB),我将调用以下函数对其进行降采样并保存较小的图像: private void downsampleLargePhoto(Uri uri, int fileSizeKB) { int scaleFactor = (int) (fileSizeKB / fileSizeLimit); log("image is " + scaleFactor +
private void downsampleLargePhoto(Uri uri, int fileSizeKB)
{
int scaleFactor = (int) (fileSizeKB / fileSizeLimit);
log("image is " + scaleFactor + " times too large");
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try
{
options.inJustDecodeBounds = false;
options.inSampleSize = scaleFactor;
Bitmap scaledBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(uri), null, options);
log("scaled bitmap has size " + scaledBitmap.getWidth() + " x " + scaledBitmap.getHeight());
String scaledFilename = uri.getPath();
log("save scaled image to file " + scaledFilename);
FileOutputStream out = new FileOutputStream(scaledFilename);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
scaledBitmap.recycle();
File image = new java.io.File(scaledFilename);
int newFileSize = (int) image.length()/1000;
log("scaled image file is size " + newFileSize + " KB");
}
catch(FileNotFoundException f)
{
log("FileNotFoundException: " + f);
}
}
但是,对于非常大的图像,我的应用程序会因OutOfMemory错误而崩溃:
Bitmap scaledBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(uri), null, options);
此时,我还能做些什么来缩小图像?您实际上还没有尝试正确使用API。您应该设置inJustDecodeBounds=true,然后调用decodeStream()。一旦确定了解码图像的大小,然后为inSampleSize选择一个合适的值,该值应该是(a)2的幂,并且(b)与压缩图像文件大小无关,然后再次调用decodeStream()
为了选择合适的inSampleSize值,我通常参考屏幕大小,即,如果图像最大边缘大于屏幕最大边缘的两倍,请将inSampleSize设置为2。等等,等等。这在[1]之前已经在这里得到了回答: