Save image from ImageView to device gallery(将 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);
}
但它需要一个我没有的文件路径,因为我从 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 中的图像保存到设备库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 ImageView 中的图像保存到设备库
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01