Android bitmap保存到系统相册

简单使用

话不多说,直接上代码,这里简易用用~ 有问题再沟通哈

   	// 相册的名字
    public static final String PIC_DIR_NAME = "wyyyPhotos";

    public static void saveBitmap2Gallery(String fileName, Bitmap bitmap) {
        File mPicDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), PIC_DIR_NAME);
        OutputStream out = null;
        String[] pathArray = null;
        String[] typeArray = null;
        try {
        	// Android 10版本 创建文件夹不成功,这里没有过多去研究
            boolean isMk = mPicDir.mkdirs();
            Log.d("ImageUtils ", "isMk = " + isMk);
            File mPicFile = new File(mPicDir, fileName + ".jpg");
            String mPicPath = mPicFile.getAbsolutePath();
            Log.d("ImageUtils ", "mPicPath = " + mPicPath);
            pathArray = new String[]{mPicFile.getAbsolutePath()};
            typeArray = new String[]{"image/jpeg"};
            ContentValues values = new ContentValues();
            ContentResolver resolver = CoreApp.getAppContext().getContentResolver();
            values.put(MediaStore.Images.ImageColumns.DATA, mPicPath);
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName);
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis() + "");
            // 插入相册
            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                out = resolver.openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                Log.d("ImageUtils ", "compress");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    Log.d("ImageUtils", "finally close");
                    // 扫描刷新
                    MediaScannerConnection.scanFile(CoreApp.getAppContext(), pathArray, typeArray, new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String s, Uri uri) {
                            Log.d("ImageUtils", "onScanCompleted  s->" + s);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

你可能感兴趣的:(Android,日常记录,android,bitmap)