将图像从ImageView保存到设备库 [英] Save image from ImageView to device gallery

查看:178
本文介绍了将图像从ImageView保存到设备库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像从ImageView保存到设备库。
我试过这段代码

I'm trying to save an image from ImageView to devices gallery. I tried this code

代码编辑:

    URL url = new URL(getIntent().getStringExtra("imageURL"));
    File f  = new File(url.getPath());

    addImageToGallery(f.getPath(), this);

    public static void addImageToGallery(final String filePath, final Context context) 
    {

       ContentValues values = new ContentValues();

       values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
       values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
       values.put(MediaStore.MediaColumns.DATA, filePath);

       context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

但是它需要一个我没有的文件路径m从URL加载文件。
如何将图像从ImageView保存到图库?

but it requires a file path in which I don't have since I'm loading the file from a URL. How can I save an image from ImageView to the gallery?

谢谢..

推荐答案

简单:

使用此代码:

//to get the image from the ImageView (say iv)
BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = draw.getBitmap();

FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();

此外,为了刷新图库并在那里查看图像:

Additionally, in order to refresh the gallery and to view the image there:

    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    sendBroadcast(intent);

还要确保您的应用已启用存储权限:

Also make sure that your app has the storage permission enabled:

进入设备设置>设备>应用程序>应用程序管理器>您的应用程序>权限>启用存储权限!

Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!

清单权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

这篇关于将图像从ImageView保存到设备库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆