我正在尝试将图像从 ImageView 保存到设备库。
我试过这段代码
代码编辑:
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 中的图像保存到图库?
thanks..
Simple:
使用此代码:
//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();
此外,为了刷新图库并查看其中的图像:
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
另请确保您的应用程序已启用存储权限:
转到设备设置>设备>应用程序>应用程序管理器>“您的应用程序”>权限>启用存储权限!
清单权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)