Here we will learn how to convert BufferedImage to byte[] in Java.
Source Code
package com.beginner.examples;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class ConvertBufferedImageToByte {
public static void main(String[] args) {
try {
URL imageURL = new URL("https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-zhidao.gif");
BufferedImage image = ImageIO.read(imageURL);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
outputStream.flush();
byte[] imageInByte = outputStream.toByteArray();
outputStream.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
References
Imported packages in Java documentation: