[英]Android App - How to save a bitmap drawing on canvas as image? Check code?
[英]How to Save bitmap to app folder in android
我有一个 bitmap,我想将它保存到 app 文件夹中。 我尝试使用这些代码:
ContextWrapper contextWrapper = new ContextWrapper(context.getApplicationContext());
File directory = contextWrapper.getDir("tabs", Context.MODE_PRIVATE);
if (!directory.exists())
directory.mkdir();
String fname = "Image.jpg";
File file = new File(directory, fname);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.close();
} catch (Exception e) {
Log.e("SAVE_IMAGE", e.getMessage(), e);
}
现在,我有两个问题。
'File.mkdir()' 的结果被忽略
你可以这样做:
try {
FileOutputStream fileOutputStream = context.openFileOutput("Your File Name", Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
它将您的 bitmap 保存在应用文件夹的“文件”目录中。
从技术上讲,您的代码是正确的,我也曾在自己的设备上尝试过,一切都是正确的。
所以我怀疑您找到了其他路径,或者如果您使用 Android Studio 检查文件,则需要单击“同步”菜单。
顺便说一句,您可以只使用 context 或 context.getApplicationContext() 来调用 getDir(),无需新建 ContextWrapper。 像这样:
File directory = context.getDir("tabs", Context.MODE_PRIVATE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/tabs";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, "Image.jpg);
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
试试这个,我希望它有帮助
这是我的答案
Result of 'File.mkdir()' is ignored
:因为 mkdir() 返回 boolean,如果创建文件夹则为true
,否则为 false。
这就是我保存 bitmap 的方法
File storageDir = getFilesDir();
File filePath = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
try (FileOutputStream out = new FileOutputStream(filePath)) {
capturedImg.compress(Bitmap.CompressFormat.JPEG, quality, out);
} catch (IOException e) {
e.printStackTrace();
}
或者如果您只想以原始分辨率保存 bitmap
public static void copy(Uri uri, File dst, Context context) {
try (InputStream in = context.getContentResolver().openInputStream(uri);
OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.