我想从服务器保存手机中的图像。图像的路径应该类似于Server.I已调试我的代码,我在这个方法中得到了正确的位图。我的代码在这个方法中失败:
public static String saveImageInPhone(Bitmap mBitmap, String imagePath, Context mContext) {
String[] iconName=imagePath.split("/");
String nameUri=imagePath.replace("/"+iconName[iconName.length-1],"").toString();
File file = new File (mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES)+nameUri, iconName[iconName.length-1]);
if (file.exists ()) file.delete ();
try {
FileOutputStream outStream = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
return file.getAbsolutePath().toString();
}
catch (FileNotFoundException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath().toString();
}
错误日志:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/package_name/files/Pictures/sample/resources/images/systemicons/conference01.png: at libcore.io.IoBridge.open(IoBridge.java:456) at java.io.FileOutputStream.<init>(FileOutputStream.java:87) at java.io.FileOutputStream.<init>(FileOutputStream.java:72) at package_name.utils.ImageUtils.saveImageInPhone(ImageUtils.java:168) at package_name.adapter.HomeFooterAdapter$1.onBitmapLoaded(HomeFooterAdapter.java:78) at com.squareup.picasso.TargetAction.complete(TargetAction.java:36) at com.squareup.picasso.Picasso.deliverAction(Picasso.java:558) at com.squareup.picasso.Picasso.complete(Picasso.java:510) at com.squareup.picasso.Picasso$1.handleMessage(Picasso.java:117) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5425) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:928) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:723) ed by: android.system.ErrnoException: open failed: ENOENT (No such file or directory) at libcore.io.Posix.open(Native Method) at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186) at libcore.io.IoBridge.open(IoBridge.java:442)
答案 0 :(得分:0)
您需要先创建文件。尝试下面的代码,让我知道它是否工作。在写这篇文章之前我已经创建了新文件。
public static String saveImageInPhone(Bitmap mBitmap, String imagePath, Context mContext) {
File file = new File (mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES), imagePath);
if (file.exists ()) file.delete ();
try {
boolean fileCreated = file.createNewFile();
if (fileCreated){
FileOutputStream outStream = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
}
}
catch (FileNotFoundException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath().toString();
}
答案 1 :(得分:0)
父目录可能不存在。使用以下代码:
File file = ...
File parentDir = file.getParent();
if(!parentDir.exists()){
parentDir.mkdirs();
}
//then save the bitmap in file