2021-04-21 11:00:08
我们需要在自己的项目中引入EncodeUtils 工具类 帮助我们进行转换
public class EncodeUtils { private static final String DEFAULT_URL_ENCODING = "UTF-8"; /** * Base64编码. */ public static String base64Encode(byte[] input) { return new String(Base64.encodeBase64(input)); } /** * Base64解码. */ public static byte[] base64Decode(String input) { return Base64.decodeBase64(input); } }
直接调用工具类中的方法即可
/*** * <p> * description: base64字符串转图片 * <p> * @see */ static void base64StringToImage(String base64String) { try { byte[] bytes1 = EncodeUtils.base64Decode(base64String); ByteArrayInputStream bais = new ByteArrayInputStream(bytes1); BufferedImage bi1 = ImageIO.read(bais); File f1 = new File("F:/wpcache/test/test.jpg"); ImageIO.write(bi1, "jpg", f1); } catch (IOException e) { e.printStackTrace(); } } /*** * <p> * description:图片转base64字符串: * <p> * @see */ public static String getImgStr(String imgFile) { https:// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 InputStream in = null; byte[] data = null; https:// 读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } return EncodeUtils.base64Encode(data); }
在main方法中运行
public static void main(String[] args) { String base64Str = getImgStr("F:/wpcache/2.jpg"); System.out.println(base64Str); base64StringToImage(base64Str); }
运行结果
图片转BASE64 效果图
BASE64 转图片 效果图
(注:这个生成的图片路径就是自己在base64StringToImage 方法中的路径)
原文链接:http://www.yuepc.com/a/18645.html
http://www.yuepc.com 为 “沈一博客” 唯一官方服务平台,请勿相信其他任何渠道。
2021-06-07
2021-07-04
2021-05-18
2021-05-12
2021-05-19
2021-05-20
2021-05-15
2021-05-11
2021-06-09
2021-05-15