android - 将图像从 ImageView 保存到存储
问题描述
我按照将图像从 ImageView 保存到内部存储中的答案进行操作,但我仍然无法保存任何内容。我的代码在这里:
public void buttonPickImage(View view) {
FileOutputStream fos;
bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
Random rng = new Random();
int n = rng.nextInt(1000);
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/BAC");
bool = dir.mkdir();
File file = new File(dir, "BAC_"+n+".jpg");
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
fos.flush();
fos.close();
Toast.makeText(getApplicationContext(),"Image sauvegardée"+bool,Toast.LENGTH_SHORT).show();
}catch (java.io.IOException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(),"IOException: " + e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
使用这种方法,我得到带有 messae 的 IOExeception :java.io.FileNotFoundException: /storage/emulated/0/BAC/BAC_396.jpg: open failed: ENOENT (No such file or directory)
我也尝试将其保存到内部存储中,但它对我不起作用: https ://www.tutorialspoint.com/how-to-write-an-image-file-in-internal-storage-in-android 有了这个方法,程序运行但布尔 mkdir 给了我错误。
谢谢你帮助我
解决方案
终于使用Media Store而不是 getExternalStorageDirectory 让它工作了
此方法在 API 级别 29 中已弃用。为了提高用户隐私,不建议直接访问共享/外部存储设备。当应用程序以 Build.VERSION_CODES.Q 为目标时,从此方法返回的路径不再可供应用程序直接访问。通过迁移到 Context#getExternalFilesDir(String)、MediaStore 或 Intent#ACTION_OPEN_DOCUMENT 等替代方案,应用程序可以继续访问存储在共享/外部存储上的内容。
MediaStore 也很有用,因为它允许您在 android 图库应用中获取图像。
所以我的解决方案是:
ImageView imageView = findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "any_picture_name");
values.put(MediaStore.Images.Media.BUCKET_ID, "test");
values.put(MediaStore.Images.Media.DESCRIPTION, "test Image taken");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outstream);
outstream.close();
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
仍然感谢@blackapps 向我解释了一些关于 IOexception、mkdir 和 toast 的基本知识。反正会有用的。
推荐阅读
- python - Python - 查找图像中直线的线性方程
- android - android ios 任何 BLE 的任何唯一密钥(我们正在使用所有 BLE - 不依赖制造商)来识别它
- javascript - 无法在 javascript (Vue.js) 应用程序中导入云函数环境变量
- android - 不可转换类型,无法将“com.example.apex.myapplication.shape”转换为“com.example.apex.myapplication.circle”
- c++ - 打开第二个窗口后隐藏主窗口?另外,当第二个窗口被用户关闭时,主窗口如何重新出现?
- java - 将超过 1000 条记录的数组从一个 jsp 传递到另一个时出错
- r - 如何显示两列与相应日期的交集?
- angular - Angular 6 客户端登录问题
- amazon-web-services - 在 pod 之间使用共享卷与每个 pod 具有自己的 pvc 卷(在 statefulset 的情况下)有什么优点和缺点?
- html - 页面元素后面的白块!(不是身体)