Search code examples
androidscreenshot

Taking screenshot programmatically in android


I am taking screenshot programmatically using the following code:

public static Bitmap takeScreenshot(View view)
    {
        try
        {
            // create bitmap screen capture
            view.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false);
            return bitmap;
        }
        catch (Throwable e)
        {
            CustomLogHandler.printError(e);
        }
        return null;
    }

private static void copyFile(Bitmap bitmap)
    {
        File dstFile = getShareResultFile();

        //Delete old file if exist.
        if(dstFile.exists()) {
            dstFile.delete();
        }

        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(dstFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
            fos.flush();
        }
        catch (Exception e) {
            CustomLogHandler.printError(e);
        }
        finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException ioe) {
                    CustomLogHandler.printError(ioe);
                }
            }
        }
    }

There are several problem like:

  1. Back arrow, title and share menu background color is not correct. It looks messy.
  2. Background color of toolbar is totally changed.
  3. Image quality is too poor and list items rounded drawable has not smooth corners.
  4. Background of layout is not taken that I set as background of my parent layout.

I am taking the screenshot from the root view.

ma


Solution

  • bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
    

    First, you are saving this as a JPEG. JPEG is designed for photos, and your screenshot is not a photo.

    Second, you are saving this with a quality factor of 0. JPEG uses a lossy compression algorithm, and a quality factor of 0 says "please feel free to make this image be really poor, but compress it as far as you can".

    I suggest switching to:

    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
    

    PNG is a better image format for a screenshot with the contents shown in your question. I don't think PNG uses the quality factor value; I put in 100 just to indicate that you want the best possible quality.