Android将base64图片保存到本地

                                                                     

 需求:将base64图片保存到图库,并且查看

1.             第一步,因为是外部存储,所以需要动态申请权限   

new RxPermissions(mActivity).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)  
        .subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {

        });

  2             第二步将base64转成bitmap

因为base64转bitmap是耗时操作,最后放在子线程中

Observable.create((ObservableOnSubscribe<Bitmap>) e -> {

    这里需要注意,如果是标准的base64的字符串,需要截取,这里需要注意下
    byte[] decode = Base64.decode(base64.split(",")[1], Base64.DEFAULT);  

    Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
    e.onNext(bitmap);
}).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
.subscribe(new Consumer<Bitmap>() {
    @Override
    public void accept(Bitmap bitmap) throws Exception {
        boolean b = saveBitmap(context, bitmap, filePath);
    }
}, new Consumer<Throwable>() {
    @Override
    public void accept(Throwable throwable) throws Exception {
        saveCallBack.save(false);
    }
});

3.         将bitmap写入文件中,更新图库

public static boolean saveBitmap(Context context,Bitmap bitmap, String path, Bitmap.CompressFormat format, int quality) {
    if (bitmap == null) {
        return false;
    }
    FileOutputStream out = null;
    try {
        boolean newFile = FileUtil.createFile(path);
        if (!newFile) {
            return false;
        }
        out = new FileOutputStream(path);
        boolean compress = bitmap.compress(format, quality, out);
        out.flush();

        //这里记得必须加入更新图片
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File savefile = new File(path);
        if (savefile.exists() && savefile.length() > 0) {
            Uri uri = Uri.fromFile(savefile);
            intent.setData(uri);
            context.sendBroadcast(intent);
        }

        return compress;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}

 

这里贴一些方法

 //获取手机相册的路径,拼接图片的名称,返回完整的路径

public static String getDiskCacheImg(String imgName) {
    String cachePath;
    cachePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath()+File.separator+imgName;
    return cachePath;
}

//创建文件的方法

public static boolean createFile(String path) throws IOException {
    boolean isSuccess = true;
    File file = new File(path);
    File parentFile = file.getParentFile();
    if (parentFile.exists()) {
        if (!parentFile.isDirectory()) {
            isSuccess &= deleteFolder(parentFile.getAbsolutePath());
            isSuccess &= createDirectory(parentFile.getAbsolutePath());
        }
    } else {
        isSuccess &= createDirectory(parentFile.getAbsolutePath());
    }

    if (!file.exists()) {
        isSuccess &= file.createNewFile();
    } else {
        if (file.isFile()) {
            return file.canRead() & file.canWrite();
        }

        isSuccess &= deleteFolder(file.getAbsolutePath());
        if (isSuccess) {
            isSuccess &= createFile(file.getAbsolutePath());
        }
    }

    return isSuccess;
}

 

public static boolean deleteFolder(String sPath) {
    boolean flag = false;
    File file = new File(sPath);
    if (!file.exists()) {
        return true;
    } else {
        return file.isFile() ? deleteFile(sPath) : deleteDirectory(sPath);
    }
}

@SuppressLint({"NewApi"})
public static boolean createDirectory(String path) {
    File dir = new File(path);
    boolean isSuccess = true;
    File parentFile = dir.getParentFile();
    if (parentFile.exists()) {
        if (!parentFile.isDirectory()) {
            isSuccess &= deleteFolder(parentFile.getAbsolutePath());
            isSuccess &= createDirectory(parentFile.getAbsolutePath());
        }
    } else {
        isSuccess &= createDirectory(parentFile.getAbsolutePath());
    }

    if (!dir.exists()) {
        isSuccess &= dir.mkdirs();
    } else {
        if (dir.isDirectory()) {
            return dir.canExecute() & dir.canRead() & dir.canWrite();
        }

        isSuccess &= deleteFolder(dir.getAbsolutePath());
        if (isSuccess) {
            isSuccess &= createDirectory(dir.getAbsolutePath());
        }
    }

    return isSuccess;
}

 

public static boolean deleteFile(String sPath) {
    boolean flag = false;
    File file = new File(sPath);
    if (!file.exists()) {
        return true;
    } else {
        if (file.isFile()) {
            flag = file.delete();
        }

        return flag;
    }
}

 

            

public static boolean deleteDirectory(String sPath) {
    if (!sPath.endsWith(File.separator)) {
        sPath = sPath + File.separator;
    }

    File dirFile = new File(sPath);
    if (!dirFile.exists()) {
        return true;
    } else if (!dirFile.isDirectory()) {
        return false;
    } else {
        boolean flag = true;
        File[] files = dirFile.listFiles();
        if (files != null && files.length > 0) {
            if (null != files) {
                for(int i = 0; i < files.length; ++i) {
                    if (files[i].isFile()) {
                        flag = deleteFile(files[i].getAbsolutePath());
                        if (!flag) {
                            break;
                        }
                    } else {
                        flag = deleteDirectory(files[i].getAbsolutePath());
                        if (!flag) {
                            break;
                        }
                    }
                }
            }

            if (!flag) {
                return false;
            } else {
                return dirFile.delete();
            }
        } else {
            return dirFile.delete();
        }
    }
}

 

具体的文件创建代码   https://download.csdn.net/download/xueyoubangbang/15450937

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将base64转化为图片保存到本地,可以使用Python的base64和PIL库来实现。 首先,需要安装PIL库,在终端或命令提示符中运行以下命令: pip install pillow 接下来,在代码中导入相关库和模块: import base64 from PIL import Image 然后,定义一个函数来将base64转化为图片保存到本地: def save_base64_image(base64_string, output_filename): # 去掉base64字符串开头的"data:image/png;base64,"部分 if base64_string.startswith('data:image/png;base64,'): base64_string = base64_string.replace('data:image/png;base64,', '') if base64_string.startswith('data:image/jpeg;base64,'): base64_string = base64_string.replace('data:image/jpeg;base64,', '') # 将base64字符串解码为二进制数据 image_data = base64.b64decode(base64_string) # 创建Image对象 image = Image.open(io.BytesIO(image_data)) # 保存图片到本地 image.save(output_filename) 最后,调用这个函数来保存图片base64_string = 'base64字符串' output_filename = '保存路径/文件名.jpg' save_base64_image(base64_string, output_filename) 通过以上步骤,你可以将base64转化为图片保存到本地。记得将base64字符串替换为你实际的base64字符串,以及设置保存路径和文件名的正确值。 ### 回答2: 要将base64转化为图片保存到本地,可以采取以下步骤: 1. 获取到base64编码的图片字符串。 2. 将base64编码的图片字符串解码为字节数据。 3. 创建一个文件对象,用于保存图片到本地。可以指定图片保存的路径和文件名。 4. 打开文件对象,以二进制写入模式写入字节数据。 5. 关闭文件对象,确保图片保存成功。 以下是一个简单的Python示例代码: ```python import base64 def save_base64_image(base64_str, save_path): # 解码base64字符串为字节数据 img_data = base64.b64decode(base64_str) # 创建文件对象 with open(save_path, 'wb') as img_file: # 写入字节数据到文件 img_file.write(img_data) print('图片保存成功!') # 测试示例 base64_str = 'data:image/png;base64,iVBORw0KGg...<省略部分内容>' save_path = 'path/to/save/image.png' save_base64_image(base64_str, save_path) ``` 此示例代码将base64编码的图片字符串解码为字节数据,并将其保存到指定路径的图片文件中。记得替换`base64_str`和`save_path`为你需要的值。执行代码后,如果没有报错,则表示图片保存成功。 ### 回答3: 使用Python语言可以很方便地将base64字符串转化为图片保存到本地。下面是一个示例代码: import base64 def save_image_from_base64(base64_str, save_path): # 移除base64字符串前的"data:image/*;base64," base64_data = base64_str.split(",")[1] # 将base64字符串解码为图片二进制数据 img_data = base64.b64decode(base64_data) # 保存图片到本地文件 with open(save_path, 'wb') as img_file: img_file.write(img_data) # 示例使用 base64_str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..." save_path = "saved_image.png" save_image_from_base64(base64_str, save_path) 在示例代码中,首先我们需要移除base64字符串前面的"data:image/*;base64,"这一段,只保留base64编码的数据部分。然后使用base64.b64decode()函数将base64字符串解码为图片的二进制数据。最后,使用open()函数创建一个二进制写入模式的文件对象,将图片数据写入文件中,完成图片保存。 你可以将上述代码保存为一个.py文件,然后通过传递base64字符串和保存路径的参数,调用save_image_from_base64()函数,即可实现将base64转化为图片保存到本地

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值