Save image from ImageView to device gallery

两盒软妹~` 提交于 2019-12-01 18:51:38

Simple:

use this code:

//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!

Manifest permissions:

<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);

Then set your image and when you want to retrieve/save it

iv.buildDrawingCache();

Bitmap bmp = iv.getDrawingCache();

Then save as normal to gallery

    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);

    }

and of course make sure your manifest has permissions to write to external storage.

U can easily get a file from URL

File f = new File(url.getPath());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!