Android截图和保存图片到指定目录

Android2023年3月25日 am8:08发布1年前 (2023)更新 3XCN.COM站长
0 0 0
广告也精彩
目录

前言

记录一下,Android截图方法和保存。

  1. 我这是系统应用测试,非系统应用需要权限的申请等
  2. Android P验证OK

正文

获取截图

public static Bitmap getScreenShot() {
    try {
        //反射 SurfaceControl screenshot()被隐藏
        String surfaceClassName = "android.view.SurfaceControl";
        @SuppressLint("PrivateApi")
        Class<?> clazz = Class.forName(surfaceClassName);
        @SuppressLint("DiscouragedPrivateApi")
        Method screenshot = clazz.getDeclaredMethod("screenshot", Rect.class, int.class, int.class, int.class);
        screenshot.setAccessible(true);
        return (Bitmap) (screenshot.invoke(clazz, new Rect(0, 0, CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight()),
                CaptureUtils.getScreenWidth(), CaptureUtils.getScreenHeight(), 0));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

CaptureUtils.getScreenWidth()和CaptureUtils.getScreenHeight()屏幕的高度
。如果是Activity中,可以用

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(dm);

如果是Service中,需要借助其他方式获取。

保存截图

private static final String mDiskPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "BiuCapture";
public static String saveBitmap(Bitmap bitmap) {
    String path = mDiskPath + File.separator + SystemClock.uptimeMillis() + ".png";
    Log.d(CaptureApp.TAG, "saveBitmap path : " + path);
    FileOutputStream fileOutputStream = null;
    try {
        File file = new File(mDiskPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(path);
        if (!file.exists()) {
            Log.d(CaptureApp.TAG, "saveBitmap createNewFile : " + file.createNewFile());
        }
        fileOutputStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
        fileOutputStream.flush();
        return path;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != fileOutputStream) {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

参考文章

  1. SurfaceControl.screenshot()用法 | SurfaceControl.screenshot()使用后返回null的解决方案
  2. Android屏幕截屏(全屏bitmap)
  3. DisplayMetrics获取宽高不对

 历史上的今天

版权声明 1、 本站名称: 91易搜
2、 本站网址: 91es.com3xcn.com
3、 本站文章: 部分来源于网络,仅供站长学习和参考,若侵权请留言
广告也精彩

相关文章

广告也精彩

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

暂无评论...

网站升级中

公告

近期网站升级中,可能存在一些bug。欢迎反馈 https://www.91es.com/we.html

本站域名

本站域名 : 91es.com3xcn.com。本站邮箱 : 站长邮箱 i@oorr.cn,通知邮箱we@oorr.cn ,如有更新,请看公告 。