简体   繁体   中英

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.

嘛

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.

public static Bitmap takeScreenshot(View view)
{
    Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);
    return bitmap;
}

This code can save view as bitmap. But after you update your question with save code I see that you set 0 for quality, and what you expect?

@param quality  Hint to the compressor, 0-100. 0 meaning compress for
     *                 small size, 100 meaning compress for max quality. Some
     *                 formats, like PNG which is lossless, will ignore the
     *                 quality setting

just use your Ctrl button + click on method name to read doc about params

the answer is set second parameter 100 instead of 0!

Try using this:

  public static Bitmap loadBitmapFromView(Context context, View v) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics(); 
        v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
                v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(returnedBitmap);
        v.draw(c);

        return returnedBitmap;
    }

and

public void takeScreen() {
    Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
    String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
    File imageFile = new File(mPath);
    OutputStream fout = null;
    try {
        fout = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
        fout.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        fout.close();
    }
}

Images are saved in the external storage folder.

try this

private void captureScreen() {
     View v =  this.getWindow().getDecorView().findViewById(android.R.id.content);
    v.setDrawingCacheEnabled(true);
    Bitmap bitmap = v.getDrawingCache();
    String extr = Environment.getExternalStorageDirectory().toString();
    File file = new File(extr, getString(R.string.free_tiket) + ".jpg");
    FileOutputStream f = null;
    try {
        f = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
        f.flush();
        f.close();
        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM