保存图片到相册并刷新相册

  /**
     * 保存图片到相册
     */
    public static boolean saveImgToPics(Context context, String path) {
        try {
            ContentResolver mResolver = context.getContentResolver();
            String insertImage = MediaStore.Images.Media.insertImage(mResolver, path, "name", "description");
            //需进行此转换操作,否则保存的图片时间为1970年的,会出现在相册的最上面
            String absPath = getRealPathFromUri(Uri.parse(insertImage), context);
            if (TextUtils.isEmpty(absPath)) {
                CrashReport.postCatchedException(new Exception("保存图片到相册失败,absPath=" + absPath));
                return false;
            }
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(absPath))));
            return true;
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
            return false;
        }
    }

    /**
     * 得到绝对地址
     */
    private static String getRealPathFromUri(Uri contentUri, Context context) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        try {
            int columnIndex = 0;
            if (cursor != null) {
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(columnIndex);
            } else {
                return "";
            }
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
            return "";
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。