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

时间:2010-05-06 13:36:35

标签: java string base64

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

3 个答案:

答案 0 :(得分:6)

答案 1 :(得分:3)

将图像转换为字符串的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中,如下所示

<img src="data:image/png;base64,iVBORw0......."/>

答案 2 :(得分:1)

用于编码和解码的Apache Commons Base64