保存图片到相册

本文介绍了一个简单的Android应用程序中实现屏幕截图的方法。通过使用特定的Activity和屏幕捕获工具,可以轻松地创建不包含状态栏的屏幕快照,并将其保存到SD卡上指定的文件夹中。此外,还介绍了如何请求外部存储权限以及如何通知系统更新相册。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//截屏
private void screenshot() {

    // 获取屏幕
    Bitmap bmp = ScreenUtil.snapShotWithoutStatusBar(this);

    if (bmp != null) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            if (hasExternalStoragePermission(mContext)) {
                File appDir = new File(Common.SCREEN_SHOT_PATH);
                if (!appDir.exists()) {
                    appDir.mkdirs();
                }
                File file = new File(appDir, "MyShareCode.jpg");
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    bmp.compress(CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //通知相册更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(file)));

                ToastUtil.showMessage(mContext, "保存成功");
            } else {

                ToastUtil.showMessage(mContext, "请打开读写内存卡权限");
            }
        } else {
            ToastUtil.showMessage(mContext, "SD卡不可用");
        }

    }

}
   public static Bitmap snapShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
//        Rect frame = new Rect();
//        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
//        int statusBarHeight = frame.top;
//
//        int width = getScreenWidth(activity);
//        int height = getScreenHeight(activity);
//        Bitmap bp = null;
//        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
//                - statusBarHeight);
//        view.destroyDrawingCache();
        return bmp;

    }
public static final String SCREEN_SHOT_PATH =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/yourname";


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值