我想将位图图像存储在外部存储中,但是在创建文件目录时遇到错误。
这是我的代码。
private void saveImage(Bitmap bitmap){
String root = Environment.getExternalStorageDirectory().toString();
File directory = new File(root + "/Wallpapers");
boolean wasSuccessful = directory.mkdirs();
if(!wasSuccessful){
Toast.makeText(context, "Error Creating directory", Toast.LENGTH_SHORT).show();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt();
String fname = "Wallpaper-"+n+".png";
File file = new File(directory, fname);
if (file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(context, "Wallpaper Saved Successfully", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(context, "Error Saving Wallpaper", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
我已经在Android清单中写入了权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
我已经尝试了许多解决方案,但无法解决我的问题。
答案 0 :(得分:0)
写一个简单的例子来存储bitmapImage图像,如下所示。请尝试一下...
//Get file name and bitmapImage and call the method ()
//Bitmap bitmapImage = ImageUtil.getInstance().changeImageRotated(cameraUri, bitmapImage, ImageUtil.TypeMode.CAMERA);
//String fileName = String.valueOf(getCurrentTimeStamp());
//ImageUtil.getInstance().saveImage(bitmapImage, fileName);
//Here is function to save bitmap image to internal storage
public Boolean saveImage(Bitmap imageData, String fileName) {
String savePath = getFilePath(AppConst.getInstance().IMAGE_DIR_APPLY);
isPathMade(savePath);
File file = new File(savePath, fileName);
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
boolean keep = true;
try {
fileOutputStream = new FileOutputStream(file);
imageData.compress(Bitmap.CompressFormat.PNG, AppConst.getInstance().PARKING_APPLY_IMAGE_COMPRESS_QUALITY, fileOutputStream);
} catch (Exception e) {
keep = false;
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (fileOutputStream != null){
fileOutputStream.close();
}
if (!keep) {
file.delete();
}
return true;
} catch (Exception e) {
Logger.e(TAG, "saveImageToCache Exception is " + e.toString());
}
}
return false;
}