简体   繁体   English

将图片从图库保存到我的文件夹外部SD中?

[英]Saving picture from gallery in my folder external SD?

I have an activity for add new post, in each post user can select picture from gallery or take picture with camera. 我有一个添加新帖子的活动,每个帖子用户都可以从图库中选择图片或使用相机拍照。 My save image method is ok for picture from camera but when I choose a picture from gallery, in my folder just save name of picture with a black picture. 对于从相机拍摄的图片,我的保存图像方法是可以的,但是当我从图库中选择图片时,在我的文件夹中只需保存带有黑色图片的图片名称。

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 "";

And in my RecyclerView shows nothing. 而且在我的RecyclerView中什么也没显示。

You are just creating a new image file and not saving anything in it . 您只是在创建一个新的图像文件,而不在其中保存任何内容。 use following 使用以下

FileOutputStream fo = new FileOutputStream(f);
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); // bmp is your Bitmap instance
fo.write(bytes.toByteArray());

you are missing this myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); 您缺少此myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fo); so add it. 所以添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM