Android 截屏保存图片

记录:

  /**
     * 1.获取和保存当前屏幕的截图
     */
    private void GetandSaveCurrentImage()
    {
        //1.构建Bitmap
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

        Bitmap Bmp;
        //2.获取屏幕
        View decorview = this.getWindow().getDecorView();
        decorview.setDrawingCacheEnabled(true);
        Bmp = decorview.getDrawingCache();

        // 获取状态栏高度
        Rect frame = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        Log.i("TAG", "" + statusBarHeight);
        Bmp = Bitmap.createBitmap(Bmp, 0, statusBarHeight, width, height - statusBarHeight);

        //保存图片
        saveImageToGallery(this,Bmp,"share.png");
    }
/**
         * 2.保存图片到指定路径
         *
         * @param context
         * @param bitmap   要保存的图片
         * @param fileName 自定义图片名称  getString(R.string.app_name) + "" + System.currentTimeMillis()+".png"
         * @return true 成功 false失败
         */
        public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
            // 保存图片至指定路径
            String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";
            Log.i("info","路径"+storePath);
            File appDir = new File(storePath);
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                //通过io流的方式来压缩保存图片(80代表压缩20%)
                boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                fos.flush();
                fos.close();

                //发送广播通知系统图库刷新数据
                Uri uri = Uri.fromFile(file);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                if (isSuccess) {
                    return true;
                } else {
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
    }

3.由于要对SDCard进行操作,所以别忘记了在manifest.xml文件中赋以对SDCard的读写权限:

 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

参考文章:

https://www.cnblogs.com/greywolf/p/3248146.html

https://blog.csdn.net/u014370269/article/details/87884475

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值