当我尝试在某些设备上保存图像时,应用程序崩溃了。
经过一些研究,我认为问题出在 imageRoot 上,但我有点迷失了这么多解决方案......
我认为问题在于获取外部存储路径。
我用来测试我的应用程序的设备没有任何 SD 卡,路径是 /mnt/sdcard/Pictures
并且图像正在成功保存。
无论手机是否有 SD 卡,我都希望它能正常工作。
提前感谢您的帮助。
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
private void saveImage() {
Bitmap bitmap = sqimage.getDrawingCache();
File image = new File(imageRoot, imageName);
if (image.exists()) {
image.delete();
}
try {
FileOutputStream output = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
new SingleMediaFileConnector(getActivity().getApplicationContext(), image);
} catch (FileNotFoundException e) {
e.printStackTrace();
success = false;
} catch (IOException e) {
e.printStackTrace();
success = false;
}
}
最佳答案
有时 getExternalStoragePublicDirectory
路径不存在。您需要检查它是否存在。
try {
imageRoot=new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "AppName");
File image = new File(imageRoot, imageName);
// Make sure the Pictures directory exists.
imageRoot.mkdirs();
// Other stuffs here
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
参见 here了解更多详情。
[编辑]
可以使用另一种方法:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
关于Android:在外部存储中保存图像的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31386620/