Android get image of a view and save it

Here is how one can save an image of a view on the device. Sometimes you need to get the image from an ImageView or simply a complex ViewGroup and save it on the device or do something with it.. here is how to do it.The method to get the image of a view is the following one:

public static Bitmap loadBitmapFromView(View view) {

        // width measure spec 
        int widthSpec = View.MeasureSpec.makeMeasureSpec(
                view.getMeasuredWidth(), View.MeasureSpec.EXACTLY);
        // height measure spec 
        int heightSpec = View.MeasureSpec.makeMeasureSpec(
                view.getMeasuredHeight(), View.MeasureSpec.EXACTLY);
        // measure the view 
        view.measure(widthSpec, heightSpec);
        // set the layout sizes 
        view.layout(view.getLeft(), view.getTop(), view.getMeasuredWidth() + view.getLeft(), view.getMeasuredHeight() + view.getTop());
        // create the bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        // create a canvas used to get the view's image and draw it on the bitmap 
        Canvas c = new Canvas(bitmap);
        // position the image inside the canvas 
        c.translate(-view.getScrollX(), -view.getScrollY());
        // get the canvas

        return bitmap;

And here is how to use the take view picture method to save the image of the view on the device:

String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
// generate the image path 
String imagePath = Environment.getExternalStorageDirectory().toString() + File.separator +  fileName + ".png";

 try {
     // save the image as png 
    FileOutputStream out = new FileOutputStream(imagePath);
    // compress the image to png and pass it to the output stream 
    loadBitmapFromView(view).compress(Bitmap.CompressFormat.PNG, 90, out);

   // save the image 

} catch (Exception error) {
      Log.e("Error saving image", error.getMessage());

If the view has some custom positioning like Gravity.CENTER or something similar, you would want to call:


This right after you took the screen shot of the view and save it.. This will get the view back to the state it was before, as the Canvas will reset the View’s image.