【Android】在res中的图片下载导入到手机相册中的实现

任务需求

产品需求是点击下载图片,将公司的二维码存储到用户手机中;

逻辑整理

实际上这张二维码没有走网络,只是在项目的res文件夹中缓存着。点击后将会读取bitmap资源然后重新存储到相册中。

代码实现

public void saveImageToGallery(Context context,ImageDownLoadCallBack imageDownLoadCallBack) {
        callBack = imageDownLoadCallBack;
        //获取二维码图片资源
        Bitmap bitmap = BitmapFactory.decodeStream(getClass().getResourceAsStream("/res/drawable/wechat_qr_consult.jpg"));
        // 文件路径资源加载
        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName = "Zego";//图片存储的文件夹名字
        File appDir = new File(file ,fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        currentFile = new File(appDir, fileName);
        FileOutputStream fos = null;

        //判断是否已经下载到相册中,如果存在直接回调存在即可,反之就进行存储在相册操作
        //进行存储操作
        try {
            fos = new FileOutputStream(currentFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //加载回调
        if (bitmap != null && currentFile.exists()) {
            callBack.onDownLoadSuccess(bitmap);
        } else {
            callBack.onDownLoadFailed();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }

    public interface ImageDownLoadCallBack {
        void onDownLoadSuccess(Bitmap bitmap);
        void onDownLoadFailed();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值