Android 保存bitmap到相册

本文介绍了一种改进的Android图片保存方法,通过覆写原生方法以增加更多参数选项,如图片创建时间与GPS位置信息等,提高了兼容性和功能性。

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

安卓原生的保存相册方法可以用但是可调参数很少,对三星这样的手机支持不好,图片的创建时间一般为1970.1.1,可以通过复写android原生的方法来添加相关参数,比如照片创建时间和gps位置信息什么的

下面是保存到相册用的函数

/**
     * Insert an image and create a thumbnail for it.
     *
     * @param cr          The content resolver to use
     * @param source      The stream to use for the image
     * @param title       The name of the image
     * @param description The description of the image
     * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored
     * for any reason.
     */
    public static String insertImage(ContentResolver cr, Bitmap source,
                                     String title, String description, String fileName) {
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, title);
        values.put(MediaStore.Images.Media.DESCRIPTION, description);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis()));
        values.put(MediaStore.Images.Media.DATE_TAKEN,System.currentTimeMillis());
);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.LATITUDE,36);
        values.put(MediaStore.Images.Media.LONGITUDE, 120);
        values.put(MediaStore.Images.Media.BUCKET_DISPLAY_NAME, "6666");


        Uri url = null;
        String stringUrl = null;    /* value to be returned */

        try {
            url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            if (source != null) {
                OutputStream imageOut = cr.openOutputStream(url);
                try {
                    source.compress(Bitmap.CompressFormat.JPEG, 36, imageOut);
                } finally {
                    imageOut.close();
                }

                long id = ContentUris.parseId(url);
                // Wait until MINI_KIND thumbnail is generated.
                Bitmap miniThumb = MediaStore.Images.Thumbnails.getThumbnail(cr, id,
                        MediaStore.Images.Thumbnails.MINI_KIND, null);
                // This is for backward compatibility.
                Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,
                        MediaStore.Images.Thumbnails.MICRO_KIND);
            } else {
                JLogUtils.i("Alex", "Failed to create thumbnail, removing original");
                cr.delete(url, null, null);
                url = null;
            }
        } catch (Exception e) {
            Log.i("Alex", "Failed to insert image", e);
            if (url != null) {
                cr.delete(url, null, null);
                url = null;
            }
        }

        if (url != null) {
            stringUrl = url.toString();
        }

        return stringUrl;
    }

    private static final Bitmap StoreThumbnail(
            ContentResolver cr,
            Bitmap source,
            long id,
            float width, float height,
            int kind) {
        // create the matrix to scale it
        Matrix matrix = new Matrix();

        float scaleX = width / source.getWidth();
        float scaleY = height / source.getHeight();

        matrix.setScale(scaleX, scaleY);

        Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
                source.getWidth(),
                source.getHeight(), matrix,
                true);

        ContentValues values = new ContentValues(4);
        values.put(MediaStore.Images.Thumbnails.KIND, kind);
        values.put(MediaStore.Images.Thumbnails.IMAGE_ID, (int) id);
        values.put(MediaStore.Images.Thumbnails.HEIGHT, thumb.getHeight());
        values.put(MediaStore.Images.Thumbnails.WIDTH, thumb.getWidth());

        Uri url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values);

        try {
            OutputStream thumbOut = cr.openOutputStream(url);

            thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
            thumbOut.close();
            return thumb;
        } catch (FileNotFoundException ex) {
            return null;
        } catch (IOException ex) {
            return null;
        }
    }

调用方法


try {
                                        ContentResolver cr = SelectPhotoActivity.this.getContentResolver();
                                        JImageUtils.insertImage(cr, currPhoto, "qraved" + JTimeUtils.getCurrentTimeLong(), "a photo from app", "我是filename没啥用");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    //对某些不更新相册的应用程序强制刷新
                                    Intent intent2 = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));//固定写法
                                    intent2.setData(uri);
                                   PhotoActivity.this.sendBroadcast(intent2);



<think>好的,用户想在Android应用中实现将图片保存到系统相册的功能。我需要根据提供的引用资料和之前的示例来组织回答。首先,引用[1]提到了关键步骤:获取权限、下载图片保存相册、更新库。引用[2]中的Toast提示可能用于通知用户保存成功。引用[4]提到从服务器获取图片的情况,但用户的问题主要是保存相册,可能涉及本地图片或下载后的图片。 我需要分步骤说明。首先,权限部分,需要互联网和存储权限,但保存相册可能需要WRITE_EXTERNAL_STORAGE,不过Android 10以上可能使用MediaStore,不需要WRITE权限?需要确认最新的权限要求。然后保存图片到公共目录,比如Pictures,使用MediaStore API。插入一条媒体记录,获取输出流,写入图片数据。如果是Bitmap,需要压缩保存。然后通知系统更新库,可能使用MediaScannerConnection扫描文件。 代码示例部分,参考引用中的代码,可能包括权限请求、保存逻辑和Toast提示。要确保代码使用正确的API,例如Context.getContentResolver()插入MediaStore.Images.Media.EXTERNAL_CONTENT_URI。注意Android版本差异,尤其是作用域存储的影响,可能需要使用MediaStore在Android 10及以上。 可能的问题点:文件路径的正确处理,避免重复文件名,处理不同Android版本的兼容性。需要提醒用户注意这些点,并提供相应的解决方法,比如使用时间戳命名文件。此外,更新库可能需要发送广播或使用MediaScannerConnection扫描文件,但后者更推荐。 最后生成相关问题,可能涉及权限处理、不同Android版本的适配、图片压缩方法等。</think>在Android应用中将图片保存至系统相册需要以下关键步骤: ### 一、权限配置 1. 在`AndroidManifest.xml`中添加存储权限: ```xml <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- Android 10+ 需要添加 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` 2. 运行时动态申请权限(针对Android 6.0+) ### 二、核心保存流程 ```java public void saveImageToGallery(Bitmap bitmap, Context context) { // 1. 创建图片存储路径 ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DISPLAY_NAME, "IMG_" + System.currentTimeMillis() + ".jpg"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // 2. 获取内容解析器 ContentResolver resolver = context.getContentResolver(); Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); // 3. 写入图片数据 try (OutputStream os = resolver.openOutputStream(uri)) { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); Toast.makeText(context, "照片已保存相册", Toast.LENGTH_SHORT).show(); // 引用[2] } catch (IOException e) { e.printStackTrace(); } // 4. 通知系统更新相册(可选) Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); mediaScanIntent.setData(uri); context.sendBroadcast(mediaScanIntent); } ``` ### 三、注意事项 1. **Android版本适配**: - Android 10+ 需使用`MediaStore API`替代直接文件路径访问 - 作用域存储(Scoped Storage)要求应用只能访问自己创建的媒体文件 2. **性能优化**: - 建议在子线程执行IO操作 - 大尺寸图片建议先压缩后保存 3. **错误处理**: - 捕获`SecurityException`(权限异常) - 处理`FileNotFoundException`(存储空间不足) ### 四、完整调用示例 ```kotlin // 检查权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { saveImageToGallery(bitmap, context) } else { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_CODE ) } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值