base64转图片并压缩zip保存到本地(一)

本文介绍了如何在Spring Boot项目中将数据库中的Base64编码转换为图片,然后进行压缩并保存为ZIP文件到本地。作者分享了实现这一功能的工具类和Controller代码片段,并欢迎读者提供优化建议。

在项目碰到这种需求,将数据库里的base64取出来,传成图片并压缩。经过一番探索,终于实现了。如果正在看这篇博客的你,还有其他更好的方法,欢迎指出!

废话少说,直接上代码!

工具类:里面有文件夹压缩方法,base64字符串转图片,本地创建和删除文件夹

package com.eastyx.authentication.utils;

import java.io.*;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import sun.misc.BASE64Decoder;

/**
 * @user: xiaobao
 * @date: 2019/4/11
 * @description 压缩zip工具类
 */
public class TestZip {

    private static final int  BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out           压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File&
### 将 Base64 编码的图片换为 URL 保存到移动设备 在 UniApp 中处理 Base64 图片将其保存本地存储涉及几个关键步骤。首先,需将 Base64 数据化为临时文件路径,之后利用 `uni.saveImageToPhotosAlbum` 方法保存该图像。 #### Base64 至临时文件路径 为了实现这目标,可创建个函数用于解析 Base64 字符串,通过 canvas API 或者调用 HBuilderX 提供的相关接口来生成对应的临时文件路径: ```javascript function base64ToFile(base64Data) { const base64 = base64Data.split(',')[1]; return new Promise((resolve, reject) => { uni.showLoading({ title: '正在保存...' }); uni.request({ url: 'data:image/png;base64,' + base64, method: 'GET', responseType: 'arraybuffer', success: function (res) { plus.io.convertBase64DataToBlob(base64, function(blob){ let tempFilePath; plus.zip.compressImage({ src: blob, dst: '_doc/images/temp.png', // 存储位置 overwrite: true, quality: 80, width: '75%', height: '75%' }, function(i){ tempFilePath = i.target; resolve(tempFilePath); }, function(e){ reject('压缩失败'); }) }); }, fail: err => { uni.hideLoading(); reject(err.errMsg || "请求失败"); } }); }); } ``` 此代码片段展示了如何接收 Base64 格式的字符串作为输入参数,返回个包含临时文件路径的结果[^1]。 #### 使用 `uni.saveImageToPhotosAlbum` 保存图片 旦获得了临时文件路径,则可以通过如下方式轻松地把这张照片存入用户的相册中: ```javascript async function saveBase64ImageToLocal(base64String) { try { const filePath = await base64ToFile(base64String); if (!filePath) throw new Error("无法获得有效的文件路径"); await uni.saveImageToPhotosAlbum({ filePath: filePath, success() { uni.showToast({ title: '已成功保存图片' }); }, complete() { uni.hideLoading(); } }); } catch(error) { console.error(`发生错误:${error.message}`); uni.showToast({ icon:'none', title:`操作失败${error.message}` }); } } ``` 上述 JavaScript 函数实现了从 Base64 到实际图片文件再到最终保存的过程。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值