图片和base64的互转

代码如下:

package com.sunyard.flowpre.service.txdapp;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author :haoc.xu
 * @date :2021/1/7 10:57
 * @Description:
 */
@Service
@Slf4j
public class TestService {
    
    

    public static void main(String[] args) {
    
    
        long start = System.currentTimeMillis();
        String imgBase64Str= TestService.convertFileToBase64("D:\\测试\\桌面.jpg");
        log.info("本地图片转换Base64:{}",imgBase64Str);
        log.info("Base64字符串length:{}",imgBase64Str.length());
        TestService.convertBase64ToFile(imgBase64Str,"D:\\测试","test.jpg");
        log.info("duration:{}",(System.currentTimeMillis()-start));
    }

    /**
     * 本地文件(图片、excel等)转换成Base64字符串
     *
     * @param imgPath
     */
    public static String convertFileToBase64(String imgPath) {
    
    
        byte[] data = null;
        // 读取图片字节数组
        try {
    
    
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小(字节)="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        // 对字节数组进行Base64编码,得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }

    /**
     * 将base64字符串,生成文件
     */
    public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
    
    

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
    
    
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {
    
    //判断文件目录是否存在
                dir.mkdirs();
            }

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);

            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            return file;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        } finally {
    
    
            if (bos != null) {
    
    
                try {
    
    
                    bos.close();
                } catch (Exception e1) {
    
    
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
    
    
                try {
    
    
                    fos.close();
                } catch (Exception e1) {
    
    
                    e1.printStackTrace();
                }
            }
        }
    }
}

效果如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/NewBeeMu/article/details/112305314