开发者

How can I convert an image to a base64 string using Java?

A开发者_如何学JAVAs the title indicates, I want to know how to convert an image to a base64 string in Java. How can I do this?


Use the Base64 class.

If you're on pre-Java 8, have a look at one of the following resources:

  • The example at exampledepot.com

  • or Base64Coder - an open-source Base64 encoder/decoder in Java

  • or the Base64 class in the org.apache.commons.codec.binary package


java code to convert image to string

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;
    }
}

and can embed it in XSL as below

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


The Apache Commons Base64 for encoding and decoding

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜