001package top.cenze.utils; 002 003import cn.hutool.core.util.StrUtil; 004import com.alibaba.fastjson.JSON; 005import org.apache.commons.codec.binary.Base64; 006 007import javax.imageio.ImageIO; 008import java.awt.image.BufferedImage; 009import java.io.ByteArrayOutputStream; 010import java.io.IOException; 011import java.io.UnsupportedEncodingException; 012 013/** 014 * base64工具类 015 */ 016public class Base64Util { 017 018 /** 019 * BufferedImage转成 base64 020 * @param bufferedImage 021 * @param imageFormatName 022 * @return 023 * @throws IOException 024 */ 025 public static String bufferedImageToBase64(BufferedImage bufferedImage, String imageFormatName) throws IOException { 026 if(StrUtil.isBlank(imageFormatName)){ 027 imageFormatName = "png"; 028 } 029 030 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 031 ImageIO.write(bufferedImage, imageFormatName, stream); 032 033 String base64 = Base64.encodeBase64String(stream.toByteArray()); 034 035 stream.flush(); 036 stream.close(); 037 038 return base64; 039 } 040 041 /** 042 * BufferedImage转成 base64 添加base64头 043 * @param bufferedImage 044 * @param imageFormatName 045 * @return 046 * @throws IOException 047 */ 048 public static String bufferedImageToBase64AddHead(BufferedImage bufferedImage, String imageFormatName) throws IOException { 049 if(StrUtil.isBlank(imageFormatName)){ 050 imageFormatName = "png"; 051 } 052 053 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 054 ImageIO.write(bufferedImage, imageFormatName, stream); 055 056 String base64 = Base64.encodeBase64String(stream.toByteArray()); 057 058 stream.flush(); 059 stream.close(); 060 061 return "data:image/" + imageFormatName + ";base64," + base64; 062 } 063 064 /** 065 * https://blog.51cto.com/u_16213386/8649945 066 * https://blog.51cto.com/u_16175504/6931837 067 * @param data 068 * @return 069 */ 070 public static String urlEncode(Object data) throws UnsupportedEncodingException { 071 return urlEncode(JSON.toJSONString(data)); 072 } 073 public static String urlEncode(String data) throws UnsupportedEncodingException { 074 return new String(Base64.encodeBase64URLSafe(data.getBytes())); 075 } 076 077 public static String urlDecode(String data) { 078 return new String(Base64.decodeBase64(data)); 079 } 080}