我在从相机活动中捕获图像、将其保存为较小尺寸并将保存的图像上传到我的服务器时遇到间歇性问题。
如果图像文件大于特定阈值(我使用 2,000KB),我将调用以下函数对其进行下采样并保存较小的图像:
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);
}
}
但是,对于非常大的图像,我的应用程序崩溃并出现 OutOfMemoryError 在线:
Bitmap scaledBitmap = BitmapFactory.decodeStream(
getContentResolver().openInputStream(uri), null, options);
此时我还能做些什么来缩小图像?