我正在尝试从相机拍摄的高分辨率图片中保存Imgefile。不幸的是,没有创建任何文件。我不知道错误在哪里。
public void saveImage(Bitmap imageFile) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName = "Image_" + timeStamp;
try {
String path = getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
File saveImage = new File(path + File.separator + imageName + ".jpg");
FileOutputStream out = new FileOutputStream(saveImage);
imageFile.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
在AndroidManifest中.xml我已经设置了写入外部存储的权限。
<manifest>
[...]
<uses-feature
android:name="android.hardware.Camera"
android:required="false" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.Camera.autofocus" />
<application
[...]>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" ></meta-data>
</provider>
[...]
</manifest>
在写入文件之前创建新文件(因为FileOutputStream
需要打开现有文件(:
File saveImage = new File(path + File.separator + imageName + ".jpg");
saveImage.createNewFile(); /// <--- add this line
FileOutputStream out = new FileOutputStream(saveImage);