如何使用Java将图像转换为base64字符串?

正如标题所示,我想知道如何在Java中将图像转换为base64字符串。 我怎样才能做到这一点?

使用Base64类。

如果您使用的是Java 8之前的版本,请查看以下资源之一:

  • exampledepot.com上的示例

  • 或Base64Coder – Java中的开源Base64编码器/解码器

  • 或org.apache.commons.codec.binary包中的Base64类

用于将图像转换为字符串的java代码

 package com.test; import java.io.IOException; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Test{ public static void main (String args[]) throws IOException { BufferedImage img = ImageIO.read(new File("C:/Test/logo.png")); BufferedImage newImg; String imgstr; imgstr = encodeToString(img, "png"); System.out.println(imgstr); } public static String encodeToString(BufferedImage image, String type) { String imageString = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); imageString = encoder.encode(imageBytes); bos.close(); } catch (IOException e) { e.printStackTrace(); } return imageString; } } 

并可以将其嵌入XSL中,如下所示

  

用于编码和解码的Apache Commons Base64