This question already has an answer here:
- File to byte[] in Java 21 answers
I want to convert an image to byte array and vice versa. Here, the user will enter the name of the image (.jpg
) and program will read it from the file and will convert it to a byte array.
Try this code snippet
Here is a complete version of code for doing this. I have tested it. The
BufferedImage
andBase64
class do the trick mainly. Also some parameter needs to be set correctly.Reference link
Check out
javax.imageio
, especiallyImageReader
andImageWriter
as an abstraction for reading and writing image files.BufferedImage.getRGB(int x, int y)
than allows you to get RGB values on the given pixel, which can be chunked into bytes.Note: I think you don't want to read the raw bytes, because then you have to deal with all the compression/decompression.