我有一个位图,我想将其保存到应用程序文件夹中。我尝试使用以下代码:
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();
}
它将位图保存在应用程序文件夹的“文件”目录中。
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();
尝试这个,希望对您有帮助
技术上您的代码是正确的,而且我在自己的设备上尝试过的所有代码都是正确的。
所以我怀疑您找到了其他路径,或者,如果您使用Android Studio检查文件,则需要单击“同步”菜单。
这是我的答案
[Result of 'File.mkdir()' is ignored
:因为mkdir()返回一个布尔值,如果创建了文件夹,则返回true
,否则返回false。
这是我保存位图的方式
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();
}
或者,如果您只想以原始分辨率保存位图,则>]
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();
}
}