美文网首页Android 开发知识
Andorid保存图片至相册功能实现

Andorid保存图片至相册功能实现

作者: hahauha | 来源:发表于2017-05-15 16:41 被阅读0次

Andorid保存图片至相册功能实现
网上能搜到解决方式普遍是方式一,但是实际测试发现,方式一是有问题的。
实现方式一:

public static void saveImageToGallery(Context context, Bitmap bmp) {
    // 首先保存图片
    File appDir = new File(Environment.getExternalStorageDirectory(), "images");
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = “myImage” + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    // 其次把文件插入到系统图库
    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // 最后通知图库更新
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
}

方式一存在的问题:
1、部分手机相册需要等待几分钟才能看见图片。如红米NOTE3
2、图库中会有两张图片存在,一张是保存的“imgaes/myImgae.jpg”,另一张是插入系统图库insertImage()方法生成的图片,通常是“系统时间.jpg。”首先在相册中出现的是后面这张图片。过会儿第一张图片也会显示在相册中。
3、insertImage()方法在红米NOTE3手机上会抛出这个异常:
MediaStore: Failed to insert image java.io.FileNotFoundException: No such file or directory at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
实现方式二:
测试可行。只保存了一张图片,并且能在相册中立即看到。

 public void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "myImage.jpg";
        final File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通知图库更新
        if (file != null && file.length() > 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    MediaScannerConnection.scanFile(
                            mContext,
                            new String[]{file.getAbsolutePath()},
                            null,
                            new MediaScannerConnection.OnScanCompletedListener() {
                                @Override
                                public void onScanCompleted(String path, Uri uri) {
                                    handler.sendEmptyMessage(0);
                                }
                            });
                }
            }).run();
        }
    }

Handle定义

    private static Handler handler=new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(mContext,"保存成功!",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            mContext.startActivity(intent);
        }
    };

方式二与方式一的区别:
1、方式二将图片直接保存在手机系统图片路径下
2、图库更新方法不同

备注:
方式一的更新图库方法也是对的,只是获取uri的方法需要改成Uri.fromFile(file),否则,就会造成方式一中的第二个问题(需要过一会儿才能在相册中看到图片)。

 mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));

相关文章

网友评论

    本文标题:Andorid保存图片至相册功能实现

    本文链接:https://www.haomeiwen.com/subject/vxuhxxtx.html