letter Q
letter Q

Reputation: 15395

Image conversion to byte array in Java

Hi I have a model testing question for a object recognition project i am working on. I want to be able to take .jpeg files I have in my eclipse project folder and reduce them to very sparse byte arrays in Java. For example if I had a picture of a ball I would like to be able to convert it to the following byte 2-D array:

00000000000000000
00000001110000000
00001100001110000
00010000000001000
00010000000001000
00001000000010000
00000011111000000
00000000000000000

If someone could be so kind as to explain how I can do this most efficiently I would greatly appreciate it. I am fairly new to programming and do not understand much more than oop so if you could describe the process in simple programming terms without any jargon I would really appreciate it.

Upvotes: 2

Views: 7286

Answers (1)

Jemish Patel
Jemish Patel

Reputation: 444

First to get byte array of image you need to convert image to BufferedImage. See ths link to convert image to BuffredImage. http://www.dzone.com/snippets/converting-images

After you get BufferedImage convert t into bytearray using bufferedImageToByteArray function.

BufferedImage buf_image; // this is BufferedImage reference you got after converting it from Image
byte[] imageByteArray = bufferedImageToByteArray(buf_image,"jpg");

public static byte[] bufferedImageToByteArray(BufferedImage image, String format) throws IOException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, format, baos);
    return baos.toByteArray();
}

Upvotes: 3

Related Questions