import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; @SuppressWarnings("restriction") public class ImageTest { static BASE64Encoder encoder = new BASE64Encoder(); static BASE64Decoder decoder = new BASE64Decoder(); public static void main(String[] args) { String img_str=image2Binary(); System.out.println(img_str); base64StringToImage(img_str); } static String image2Binary(){ File f = new File("e:/a.gif"); BufferedImage bi; try { bi = ImageIO.read(f); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bi, "jpg", baos); byte[] bytes = baos.toByteArray(); return encoder.encodeBuffer(bytes).trim(); } catch (IOException e) { e.printStackTrace(); } return null; } static void base64StringToImage(String base64String){ try { byte[] bytes = decoder.decodeBuffer(base64String); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); BufferedImage bi =ImageIO.read(bais); File file = new File("e:/a.png"); ImageIO.write(bi, "jpg", file); } catch (IOException e) { e.printStackTrace(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步