カメラ アクティビティから画像をキャプチャし、小さいサイズで保存し、保存した画像をサーバーにアップロードする際に断続的に問題が発生します。
画像ファイルが特定のしきい値 (私は 2,000 KB を使用) よりも大きい場合、次の関数を呼び出してダウンサンプリングし、小さい画像を保存します。
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);
この時点で、画像を縮小するために他に何ができますか?