[英]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.