将图像从ImageView保存到设备库

Ela*_*dit 4 android imageview android-gallery android-imageview

我正在尝试将图像从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);
    }
Run Code Online (Sandbox Code Playgroud)

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

谢谢..

Shr*_* DG 15

简单:

使用此代码:

//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();
Run Code Online (Sandbox Code Playgroud)

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

    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    intent.setData(Uri.fromFile(file));
    sendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

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

转到设备设置>设备>应用程序>应用程序管理器>"您的应用程序">权限>启用存储权限!

清单权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)