我有一个添加新帖子的 Activity ,在每个帖子中,用户可以从图库中选择图片或用相机拍照。我的保存图片方法适用于来自相机的图片,但是当我从图库中选择图片时,在我的文件夹中只保存带有黑色图片的图片名称。
public void saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
img_name = f.getAbsolutePath();
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
而在我的 RecyclerView 中什么也没显示。
最佳答案
您只是创建了一个新的图像文件,并没有在其中保存任何内容。 使用以下
FileOutputStream fo = new FileOutputStream(f);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap instance
fo.write(bytes.toByteArray());
你缺少这个 myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo);
所以添加它。
关于java - 将图库中的图片保存在我的外部 SD 文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53702432/