仿比心源码,保存图片到系统相册

2020-12-23 17:53:40 浏览数 (1)

仿比心源码,保存图片到系统相册的相关代码

代码语言:javascript复制
    //保存图片
    public static void scanFile(File file){
            String mimeType = getMimeType(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            String fileName = file.getName();
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME,fileName);
            values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
            ContentResolver contentResolver = context.getContentResolver();
            Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if(uri == null){
                ToastUtils.showShort("图片保存失败");
                return;
            }
            try {
                OutputStream out = contentResolver.openOutputStream(uri);
                FileInputStream fis = new FileInputStream(file);
                FileUtils.copy(fis,out);
                fis.close();
                out.close();
                ToastUtils.showShort("图片保存成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            MediaScannerConnection.scanFile(Utils.getApp(), new String[]{file.getPath()}, new String[]{mimeType}, (path, uri) -> {
                ToastUtils.showShort("图片已成功保存到"   path);
            });
        }
    }
    public static String getMimeType(File file){
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(file.getName());
        return type;
}

以上就是仿比心源码,保存图片到系统相册的相关代码, 更多内容欢迎关注之后的文章

0 人点赞