android - 我正在尝试保存从 Android 相机拍摄的照片,但收到 OutOfMemoryError 错误
问题描述
我正在尝试保存从 Android 相机拍摄的照片,但出现以下错误
抛出 OutOfMemoryError “无法分配 51916812 字节分配,其中 12763771 个可用字节和 12MB 直到 OOM”
我想以最佳图像质量存储它。
可能吗?
下面是源代码
private class SaveImageTask extends AsyncTask<byte[], Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(byte[]... data) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeByteArray(data[0], 0, data[0].length, options);
Log.i("sinwhod","matrix = " + orientation);
Matrix matrix = new Matrix();
//matrix.postRotate(orientation);
matrix.setRotate(orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] currentData = stream.toByteArray();
Date day = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
fileName = String.valueOf(sdf.format(day));
savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
temp = savePath + "/" + fileName + ".jpg";
File file = new File(temp);
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(currentData);
fos.flush();
fos.close();
} catch (Exception e) {
Log.i("sinwhod", "error = " + e);
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + temp)));
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(MainActivity.this, temp, Toast.LENGTH_SHORT).show();
}
}
'''
解决方案
推荐阅读
- flutter - 可用于 Flutter 的最低版本的 Dart 是什么?
- python - 我可以通过重用它的值来初始化一个python对象吗?
- c# - 从类中的同一解决方案中读取另一个项目中的 AppSetting.json 设置
- heroku - 如何处理 Heroku 上的大量 slug 大小?
- javascript - 更改时间格式
- ngrx - 没有调用ngrx减速器
- java - App Engine 部署失败:进程处理程序异常 - 非零退出 [2]
- wordpress - 图标控制 | 元素
- ios - 'FacebookCore' 没有指定 Swift 版本,并且集成它的目标('AppName')都没有设置'SWIFT_VERSION'属性
- asp.net-core - 使用 OpenID Connect 授权代码流从 Okta 获取“组”声明