Save image from ImageView to device gallery

后端 未结 3 1303
臣服心动
臣服心动 2021-01-18 18:23

I\'m trying to save an image from ImageView to devices gallery. I tried this code

Code Edit:

    URL url = new URL(getIntent().getStringExtra(\"image         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 18:47

    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.

提交回复
热议问题