Search code examples
androidandroid-imageviewandroid-bitmap

How to store background image from imageView in bitmap?


I am trying to store my image from imageView in bitmap, so that I can store it in the gallery of the android device. Every time I save an image, the background of the imageView is not stored. What am I missing?

Here is my code:

ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();

Code to store the image into the gallery is:

FileOutputStream outStream = null;
            File dir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "MyAlbum");
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    Log.d("MyAlbum", "failed to create directory");
                    Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
                }
            }
            String fileName = String.format("%d.jpg", System.currentTimeMillis());
            File outFile = new File(dir, fileName);
            try {
                outStream = new FileOutputStream(outFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                outStream.flush();
                outStream.close();

                Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intent.setData(Uri.fromFile(dir));
                sendBroadcast(intent);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

Solution

  • You can take a screenshot of this view (ImageView) in this case, it will simply take what's drawn on this view at this moment and turn it into a bitmap you can save.

    Answer is mentioned here already.

    The magical part is that

    ImageView yourImageView = .. // Get reference it to your view.
    yourImageView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
    yourImageView.setDrawingCacheEnabled(false);
    

    Ta-da you can use your snapshot btimap.