Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java is it possible to convert a BufferedImage to an IMG Data URI?

I have created a graphical image with the following sample code.

BufferedImage bi = new BufferedImage(50,50,BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g2d = bi.createGraphics();

// Draw graphics. 

g2d.dispose();
// BufferedImage now has my image I want.

At this point I have BufferedImage which I want to convert into an IMG Data URI. Is this possible? For example..

<IMG SRC="data:image/png;base64,[BufferedImage data here]"/>
like image 930
Jiyeon Avatar asked Jun 16 '11 19:06

Jiyeon


3 Answers

Not tested, but something like this ought to do it:

ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "PNG", out);
byte[] bytes = out.toByteArray();

String base64bytes = Base64.encode(bytes);
String src = "data:image/png;base64," + base64bytes;

There are lots of different base64 codec implementations for Java. I've had good results with MigBase64.

like image 74
Matt Ball Avatar answered Nov 07 '22 04:11

Matt Ball


You could use this solution which doesn't use any external libraries. Short and clean! It uses a Java 6 library (DatatypeConverter). Worked for me!

ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(image, "png", output);
DatatypeConverter.printBase64Binary(output.toByteArray());
like image 36
FranciscoBouza Avatar answered Nov 07 '22 03:11

FranciscoBouza


I use Webdriver, get captcha, like this below:

// formatName -> png
// pathname -> C:/Users/n/Desktop/tmp/test.png
public static String getScreenshot(WebDriver driver, String formatName, String pathname) {
    try {
        WebElement element = driver.findElement(By.xpath("//*[@id=\"imageCodeDisplayId\"]"));
        File screenshot = element.getScreenshotAs(OutputType.FILE);
        // base64 data
        String base64Str = ImageUtil.getScreenshot(screenshot.toString()); 
        return base64Str;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static String getScreenshot(String imgFile) {
    InputStream in;
    byte[] data = null; 
    try {
        in = new FileInputStream(imgFile);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String base64Str = new String(Base64.getEncoder().encode(data));
    if (StringUtils.isAnyBlank(base64Str)) {
        return null;
    }
    if (!base64Str.startsWith("data:image/")) {
        base64Str = "data:image/jpeg;base64," + base64Str;
    }
    return base64Str;
}
like image 33
JTL Avatar answered Nov 07 '22 04:11

JTL