首页 > 其他 > 详细

图片与base64转换

时间:2021-04-12 22:52:02      阅读:59      评论:0      收藏:0      [点我收藏+]

`

/**
* @Description: base64字符串转化成图片
* @Param:
* @return:
* @throws Exception
* @author: hw
* @date: 2021/4/12 15:45
*/
public static boolean GenerateImage(String imgStr, String path) {
    //对字节数组字符串进行Base64解码并生成图片
    if (imgStr == null) //图像数据为空
        return false;

    BASE64Decoder decoder = new BASE64Decoder();
    try {
        //Base64解码
        byte[] b = decoder.decodeBuffer(imgStr);
        for(int i=0;i<b.length;++i) {
            if(b[i]<0) {//调整异常数据
                b[i]+=256;
            }
        }
        //生成jpeg图片
        OutputStream out = new FileOutputStream(path);
        out.write(b);
        out.flush();
        out.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

/**
* @Description: 将MultipartFile 图片文件编码为base64
* @Param:
* @return:
* @throws Exception
* @author: hw
* @date: 2021/4/12 19:16
*/
public static String generateBase64(MultipartFile file){
    if (file == null || file.isEmpty()) {
        throw new RuntimeException("图片不能为空!");
    }
    String fileName = file.getOriginalFilename();
    String fileType = fileName.substring(fileName.lastIndexOf("."));
    String contentType = file.getContentType();
    byte[] imageBytes = null;
    String base64EncoderImg="";
    try {
        imageBytes = file.getBytes();
        BASE64Encoder base64Encoder =new BASE64Encoder();
        /**
         * 1.Java使用BASE64Encoder 需要添加图片头("data:" + contentType + ";base64,"),
         *   其中contentType是文件的内容格式。
         * 2.Java中在使用BASE64Enconder().encode()会出现字符串换行问题,这是因为RFC 822中规定,
         *   每72个字符中加一个换行符号,这样会造成在使用base64字符串时出现问题,
         *   所以我们在使用时要先用replaceAll("[\\s*\t\n\r]", "")解决换行的问题。
         */
        base64EncoderImg = "data:" + contentType + ";base64," + base64Encoder.encode(imageBytes);
        // base64EncoderImg = base64Encoder.encode(imageBytes);
        base64EncoderImg = base64EncoderImg.replaceAll("[\\s*\t\n\r]", "");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return base64EncoderImg;
}`

图片与base64转换

原文:https://www.cnblogs.com/weihuang6620/p/14649704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!