android 11及以上保存图片视频到相册

这篇具有很好参考价值的文章主要介绍了android 11及以上保存图片视频到相册。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Android 10之前版本主要步骤

  1. 请求读写权限
  2. 图片/视频下载到/storage/emulated/0/Android/data/包名/xxx
  3. 复制到系统相册目录下
  4. 扫描媒体库

Android 10及以上版本主要步骤

  1. 请求读写权限
  2. 图片/视频下载到/storage/emulated/0/Android/data/包名/xxx
  3. 创建ContentValues,写入要保存的信息
  4. 调用ContentResolver插入ContentValues到相册中,此时会返回新创建的相册uri
  5. 将原先的文件复制到该uri中(android11及以上必须这么干)
  6. 发送广播,扫描媒体库

关键代码:

public class SaveUtils {
    private static final String TAG = "SaveUtils";

    /**
     * 将图片文件保存到系统相册
     */
    public static boolean saveImgFileToAlbum(Context context, String imageFilePath) {
        Log.d(TAG, "saveImgToAlbum() imageFile = [" + imageFilePath + "]");
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath);
            return saveBitmapToAlbum(context, bitmap);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将bitmap保存到系统相册
     */
    public static boolean saveBitmapToAlbum(Context context, Bitmap bitmap) {
        if (bitmap == null) return false;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return saveBitmapToAlbumBeforeQ(context, bitmap);
        } else {
            return saveBitmapToAlbumAfterQ(context, bitmap);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private static boolean saveBitmapToAlbumAfterQ(Context context, Bitmap bitmap) {
        Uri contentUri;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }
        ContentValues contentValues = getImageContentValues(context);
        Uri uri = context.getContentResolver().insert(contentUri, contentValues);
        if (uri == null) {
            return false;
        }
        OutputStream os = null;
        try {
            os = context.getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                Files.copy(bitmapFile.toPath(), os);
//            }
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            context.getContentResolver().update(uri, contentValues, null, null);
            return true;
        } catch (Exception e) {
            context.getContentResolver().delete(uri, null, null);
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean saveBitmapToAlbumBeforeQ(Context context, Bitmap bitmap) {
        File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File destFile = new File(picDir, context.getPackageName() + File.separator + System.currentTimeMillis() + ".jpg");
//            FileUtils.copy(imageFile, destFile.getAbsolutePath());
        OutputStream os = null;
        boolean result = false;
        try {
            if (!destFile.exists()) {
                destFile.getParentFile().mkdirs();
                destFile.createNewFile();
            }
            os = new BufferedOutputStream(new FileOutputStream(destFile));
            result = bitmap.compress(Bitmap.CompressFormat.JPEG, 50, os);
            if (!bitmap.isRecycled()) bitmap.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        MediaScannerConnection.scanFile(
                context,
                new String[]{destFile.getAbsolutePath()},
                new String[]{"image/*"},
                (path, uri) -> {
                    Log.d(TAG, "saveImgToAlbum: " + path + " " + uri);
                    // Scan Completed
                });
        return result;
    }

    /**
     * 获取图片的ContentValue
     *
     * @param context
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static ContentValues getImageContentValues(Context context) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() + ".jpg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + File.separator + context.getPackageName());
        contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
        contentValues.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        contentValues.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis());
        contentValues.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        return contentValues;
    }

    /**
     * 将视频保存到系统相册
     */
    public static boolean saveVideoToAlbum(Context context, String videoFile) {
        Log.d(TAG, "saveVideoToAlbum() videoFile = [" + videoFile + "]");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return saveVideoToAlbumBeforeQ(context, videoFile);
        } else {
            return saveVideoToAlbumAfterQ(context, videoFile);
        }


    }

    private static boolean saveVideoToAlbumAfterQ(Context context, String videoFile) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            File tempFile = new File(videoFile);
            ContentValues contentValues = getVideoContentValues(context, tempFile, System.currentTimeMillis());
            Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
            copyFileAfterQ(context, contentResolver, tempFile, uri);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            context.getContentResolver().update(uri, contentValues, null, null);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean saveVideoToAlbumBeforeQ(Context context, String videoFile) {
        File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        File tempFile = new File(videoFile);
        File destFile = new File(picDir, context.getPackageName() + File.separator + tempFile.getName());
        FileInputStream ins = null;
        BufferedOutputStream ous = null;
        try {
            ins = new FileInputStream(tempFile);
            ous = new BufferedOutputStream(new FileOutputStream(destFile));
            long nread = 0L;
            byte[] buf = new byte[1024];
            int n;
            while ((n = ins.read(buf)) > 0) {
                ous.write(buf, 0, n);
                nread += n;
            }
            MediaScannerConnection.scanFile(
                    context,
                    new String[]{destFile.getAbsolutePath()},
                    new String[]{"video/*"},
                    (path, uri) -> {
                        Log.d(TAG, "saveVideoToAlbum: " + path + " " + uri);
                        // Scan Completed
                    });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (ins != null) {
                    ins.close();
                }
                if (ous != null) {
                    ous.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyFileAfterQ(Context context, ContentResolver localContentResolver, File tempFile, Uri localUri) throws IOException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
                context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
            //拷贝文件到相册的uri,android10及以上得这么干,否则不会显示。可以参考ScreenMediaRecorder的save方法
            OutputStream os = localContentResolver.openOutputStream(localUri);
            Files.copy(tempFile.toPath(), os);
            os.close();
            tempFile.delete();
        }
    }


    /**
     * 获取视频的contentValue
     */
    public static ContentValues getVideoContentValues(Context context, File paramFile, long timestamp) {
        ContentValues localContentValues = new ContentValues();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM
                    + File.separator + context.getPackageName());
        }
        localContentValues.put(MediaStore.Video.Media.TITLE, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, paramFile.getName());
        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
        localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, timestamp);
        localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, timestamp);
        localContentValues.put(MediaStore.Video.Media.DATE_ADDED, timestamp);
        localContentValues.put(MediaStore.Video.Media.SIZE, paramFile.length());
        return localContentValues;
    }

}



 文章来源地址https://www.toymoban.com/news/detail-513756.html

到了这里,关于android 11及以上保存图片视频到相册的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Flutter】支持多平台 多端保存图片到本地相册 (兼容 Web端 移动端 android 保存到本地)

    免责声明: 我只测试了Web端 和 Android端 可行哈

    2024年02月09日
    浏览(44)
  • android studio开发——android11版本以上权限动态申请问题,包括文件读写、图片、相机的调用

    用于android手机的升级,现在已经是android13版本了,对于权限问题可能更加敏感了,前段时间开发发现之前的方法已经不再适用于android11以后的版本了 读写权限申请最好是跳转到设置中进行才是最好了,下面我们开始进行 首先是AndroidManifest.xml文件的权限 然后这里讲解一下权

    2024年02月10日
    浏览(47)
  • qt ios 将图片和视频保存到手机相册里

    需要先将QImage保存到App的路径里 /var/mobile/Containers/Data/Application/xxxxxx/Documents/Pictures/ 使用 UIImage 读取路径图片 然后再调用 UIImageWriteToSavedPhotosAlbum() 将图片保存到手机相册 还有一种方法是将 QImage 数据拷贝到 UIImage 里, 可以在网上查找 视频文件也是先保存到App路径里 注意视频

    2024年02月04日
    浏览(34)
  • Android开发 拍照+读取相册+保存到本地

    注册除了MainActivity的其他两个界面Albums和Camera,添加provider,申请使用相机的权限,读写权限 file_path.xml代码 如果虚拟机可以运行,手机不能安装,gradle.properties里面添加 文件结构 总结 https://wwzb.lanzoue.com/imUKH0n1nq4d 密码:1eda 分享Demo可试试效果 参考来源:  Android studio调用手机

    2024年02月05日
    浏览(38)
  • Android---打开相册选择图片

    简单实现打开系统相册选择一张图片并显示在UI上,适用与个人主页头像的切换。 1. 添加存储权限。AndroidManifest.xml里添加读取内存的权限。 2. 布局。布局内容比较交单,一个Button用来打开相册;一个ImageView用来接收从相册选择的图片。 3. 动态申请权限。Google 在 Android  6.0

    2024年02月03日
    浏览(27)
  • Android存储权限完美适配(Android11及以上适配)

    一、Bug简述 一个很普通的需求,需要下载图片到本地,我的三个测试机(荣耀Android10,红米 11 和小米Android 13都没有问题)。 然后,主角登场了,测试的三星Android 13 死活拉不起存储权限弹窗。 想了下,三星的系统可能和小米的系统做了些区别。于是就是看了下存储权限的版

    2024年02月06日
    浏览(35)
  • UE4实现截屏并保存到相册Android/iOS兼容

    通过Edit-Plugins-NewPlugin创建3个空的Plugin: MyNative插件,实现截屏功能,并提供对外调用的接口 MyNativeAndroid插件,实现Android端保存图片到相册功能 MyNativeIos插件,实现iOS端保存图片到相册功能 1.在MyNative.uplugin注册引用到2个插件MyNativeAndroid和MyNativeIos 2.在MyNative.Build.cs分平台引用

    2024年02月15日
    浏览(36)
  • Android11及以上 文件读写权限申请

    Android11 读写权限申请 Android11系统对应用写入权限做了严格的限制。本文介绍如何获取文件读写权限。项目中 build.gradle 的 targetSdkVersion = 29 ,会出现读写问题。 当 targetSdkVersion = 29,通过设置requestLegacyExternalStorage=“true”,还能解决。 当 targetSdkVersion = 30后,需要申请所有文件

    2023年04月10日
    浏览(44)
  • Android webview上传图片(调起相册/相机上传)

    概述 默认情况 WebView 不支持input type=file,WebView 点击没有反应。 兼容 重写 webview 的 webchromeClient 中的 openFileChooser 方法。Android 版本的多样性,就理所当然的各种兼容。 具体代码实现 网上也有很多实现方式,这边记录一下自己用到的一种 webview 调用时,弹出本地弹框,选择(

    2023年04月21日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包