hussain
hussain

Reputation: 155

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

As the title indicates, I want to know how to convert an image to a base64 string in Java. How can I do this?

Upvotes: 11

Views: 29877

Answers (3)

Raman B
Raman B

Reputation: 339

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......."/>

Upvotes: 6

aioobe
aioobe

Reputation: 420981

Use the Base64 class.

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

Upvotes: 6

Lars
Lars

Reputation: 1121

The Apache Commons Base64 for encoding and decoding

Upvotes: 0

Related Questions