java base64 图片

package com.xx.xx.xx;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Author: fy 
 * @Date: 2019/4/25 13:42
 * @Description:  base64 和图片的转化
 */
public class MyBase64PictureUtils {


    /**
     * 将图片转成base64  这种base64没有头信息,如 data:image/png;base64,
     * @param picturePath  图片的绝对路径
     * @return  base64
     */
    public  static String picture2Base64(String picturePath){
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(picturePath);
            data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException(e);
        }finally {
            IOUtils.closeQuietly(in);
        }
    }


    /**
     * 将base64转成图片,如果 base64以头信息开头如 data:image/png;base64,*****,需要将 data:image/png;base64,去掉才能转成图片
     * @param base64
     */
    public static  void createPictureByBase64(String base64,String saveFilePath) throws  Exception{

        if(base64.startsWith("data:")){
            base64 = base64.substring(base64.indexOf(",")+1);
        }
        BASE64Decoder decoder =new BASE64Decoder();
        byte[] bytes = decoder.decodeBuffer(base64);
        FileUtils.writeByteArrayToFile(new File(saveFilePath),bytes);
    }


}

io包我用了 apache common-io里面工具。

java生成base64或者 生成图片是不需要data:image/png;base64 这样的头信息的。但是有时候前端传过来的图片base64包含这样的信息。所以如果要保存为图片,需要去掉这样的头信息。

   毕竟浏览器直接使用base64资源,肯定是需要知道数据的类型的。

base64保存为图片的时候如果要求不高可是直接后缀为  

C:\***\**\**\**.png ,否则就要去读取head信息里面的类型如 data:image/png;base64    ,或 data:image/jpeg;base64
原文地址:https://www.cnblogs.com/fangyuandoit/p/13713827.html