我正在开发Android上的图像操作应用程序,但我一直在编写图像保存代码。即使拥有用户权限,也无法保存外部存储上的文件[Android]
这是我使用的方法:
private void saveImageToExternalStorage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
我每次执行此,FileOutputStream中给出了一个FileNotFoundException异常。
我的清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gabrielerestuccia.testimmagini">
<application
...
</application>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
我开发这个在Android 1.5.1工作室在Linux上,使用内置虚拟的Nexus 5采用Android 6.0。
感谢您的帮助。
https://stackoverflow.com/questions/32635704/cant-get-the-permission – CommonsWare
'每次我执行这个时,FileOutputStream都会给出一个FileNotFoundException'。但你仍在呼叫媒体扫描仪。更好:回归声明。 – greenapps
'myDir.mkdirs();'。你应该检查返回值,如果为false则不能继续。如果目录已经存在,不要调用mkdirs。 – greenapps