Android 根据源图片文件路径,保存到相册,并刷新相册显示

做creator游戏开发时,有需求保存图片到相册目录

接触安卓不多,如有错误欢迎大佬指出。。。

//文件保存到相册
public static void savePhotoFile(String fromPath) {
    File fromFile = new File(fromPath);
    if(!fromFile.exists()) {
        System.out.println("源文件不存在");
        return;
    }
    if (!fromFile.isFile()){
        System.out.println("源文件不是文件");
        return;
    }
    try {
        //方法一
        //复制文件到指定目录下
        String toPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM/Camera/";
        File toFile = new File(toPath);
        if (!toFile.exists()) {
            toFile.mkdir();//没有该目录,创建一个
        }
        FileInputStream fromStream = new FileInputStream(fromPath);    //读入原文件
        FileOutputStream toStream = new FileOutputStream(toPath + fromFile.getName());
        byte[] buffer = new byte[1024];
        int len;
        while ((len= fromStream.read(buffer)) > 0){
            toStream.write(buffer, 0, len);
        }
        fromStream.close();
        toStream.flush();
        toStream.close();
        //刷新相册
        Context context = AppActivity.getContext();
        MediaStore.Images.Media.insertImage(context.getContentResolver(),fromFile.getAbsolutePath(), fromFile.getName(), null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File(toPath));
        intent.setData(uri);
        context.sendBroadcast(intent);

        fromFile.delete();//删除源文件

        //方法二
        //获得源文件路径,直接把插入到系统图库,可能并不是DCIM目录下
        /*Context context = AppActivity.getContext();
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    fromFile.getAbsolutePath(), fromFile.getName(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(fromFile.getParent()))));*/
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值