
base64编码字符串和图片的互转
发布日期:2021-05-07 14:53:54
浏览次数:14
分类:原创文章
本文共 1749 字,大约阅读时间需要 5 分钟。
新建一个Base64ImageUtils类
package com.demo.test;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;public class Base64ImageUtils { /** * 将base64编码字符串转换为图片 * @param base64Code * @param outputPath * @return */ public static boolean generateImage(String base64Code,String outputPath) { if (base64Code == null) { return false; } BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(base64Code); for (int i = 0; i < b.length; i++) { if (b[i] < 0) { b[i]+= 256; } } OutputStream out = new FileOutputStream(outputPath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 根据图片地址转换为base64编码字符串 * @param imagePath * @return */ public static String getBase64Code(String imagePath) { InputStream input = null; byte[] data = null; try { input = new FileInputStream(imagePath); data = new byte[input.available()]; input.read(data); input.close(); } catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data); } }
测试类:
package com.demo.test;public class Base64Test { public static void main(String[] args) { String base64Code = Base64ImageUtils.getBase64Code("F:\\Test\\shop\\WebRoot\\products\\405964b4-bf81-470c-8ee6-fed1aaf35b4194d9458f-6b65-4b1c-9577-0928a4818de0.jpg");//这是你转换的图片路径 System.out.println(base64Code); Base64ImageUtils.generateImage(base64Code, "C:\\Users\\zhangjie\\Desktop\\psb.webp1.jpg");//这是你获取的Base64编码在生成一个新的图片的路径名 }}
图片转换器的地址: