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 中的图像保存到设备库
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01