Android UiAutomation take compressed screenshot

Refer to:
https://developer.android.com/reference/androidx/test/uiautomator/UiDevice

storePath   File: where the PNG should be written to
scale   float: scale the screenshot down if needed; 1.0f for original size
quality int: quality of the PNG compression; range: 0-100

boolean takeScreenshot (File storePath, 
                float scale, 
                int quality)

But it's using the following code:

Bitmap screenshot = this.getUiAutomation().takeScreenshot();
...
bos = new BufferedOutputStream(new FileOutputStream(storePath));
...
screenshot.compress(CompressFormat.PNG, quality, bos);

While in Bitmap.java:

Write a compressed version of the bitmap to the specified outputstream. If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream(). Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).
Params:
format – The format of the compressed image
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
stream – The outputstream to write the compressed data.
Returns:
true if successfully compressed to the specified stream.

public boolean compress(CompressFormat format, int quality, OutputStream stream)

We take screenshots with the format CompressFormat.PNG by default, which then cannot be directly compressed.

So we can make our own method to take screenshots(We can also take the format as an optional param):

    boolean takeScreenshot(String storePath, int quality) {
        UiAutomation automation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Bitmap screenshot = automation.takeScreenshot();
        if (screenshot != null) {
            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("/sdcard/Download/" + storePath + ".jpeg"))) {
                screenshot.compress(Bitmap.CompressFormat.JPEG, quality, bos);
                bos.flush();
                return true;
            } catch (IOException ex) {
                Log.e(TAG, "failed to save screen shot to file", ex);
            } finally {
                screenshot.recycle();
            }

        }
        return false;
    }
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容