![](/img/trans.png)
[英]Save Image (took with Camera Intent) from ImageView to device (Gallery/SdCard)
[英]Save image from ImageView to device gallery
我正在嘗試將圖像從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保存到圖庫?
謝謝..
簡單:
使用此代碼:
//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" />
ImageView iv = (ImageView)findViewById(R.id.your_image_view);
然后設置圖像以及何時要檢索/保存圖像
iv.buildDrawingCache();
Bitmap bmp = iv.getDrawingCache();
然后像往常一樣保存到圖庫
File storageLoc = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); //context.getExternalFilesDir(null);
File file = new File(storageLoc, filename + ".jpg");
try{
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
scanFile(context, Uri.fromFile(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private static void scanFile(Context context, Uri imageUri){
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(imageUri);
context.sendBroadcast(scanIntent);
}
當然要確保您的清單有權寫入外部存儲。
你可以輕松地從URL獲取文件
File f = new File(url.getPath());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.