How to Convert Image to Bytes in Java
Computers store images as binary data files. The file for a given image depends on the image's contents (its size, color depth, and the color components for each pixel) and on the method used to encode the image. Standard methods such as JPEG and PNG are very common. A Java application may read an encoded image to display it, or even to apply transformations to it. That typically implies reading the image file into a Java byte array.
Instructions
-
-
1
Include the following line at the beginning of your Java code:
import org.apache.commons.io. IOUtils;
-
2
Open the file containing the image as a Java FileInputStream, as in the following sample code:
FileInputStream myStream = new FileInputStream("imageFile.jpg");
-
-
3
Read the input stream into an array of bytes by calling the toByteArray() library method, as in the following sample code:
byte[] imageInBytes = IOUtils.toByteArray(myStream);
Byte array "imageInBytes" will contain the bytes corresponding to the image in the file.
-
1