java - 将图库中的图片保存在我的外部 SD 文件夹中?

标签 java android sqlite

我有一个添加新帖子的 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/

相关文章:

java - 当看不到 java 7 时,Jwrapper 因 java 7 invokedynamic 的类版本错误而失败

android - 使用 Google App Engine 在 Android 中推送通知

android - 哪些广告网络在向用户支付真钱时允许奖励视频?

sqlite - 如何为 WinRT/ARM 编译 sqlite?

java - BeanIO unquotedQuotesAllowed 在 CSV 中不起作用

java - 使用@Embedded 和@Id 的Hibernate 复合主键

java - 如何在我的代码中放置输入流进度监视器?

android - 具有种子作用的随机数生成非确定性

node.js - 如何将 sqlite3 模块与 Electron 一起使用?

database - 如何在 SQLIte 中获取子字符串?