1

I have a strange issue with ByteArrayOutputStream. I am trying to input an image and convert it to an array of bytes. The image is 270 x 480 pixels. However if I set data to the byte array and output data.length I get 21195 however 270 x 480 = 129600. Shouldn't they be the same? What am I doing wrong here?

BufferedImage originalImage =
                                  ImageIO.read(new File("C:\\Users\\use\\Pictures\\mypic.jpg"));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write( originalImage, "jpg", baos );
        baos.flush();
        data = baos.toByteArray();
        baos.close();

thanks,

jacksonecac
  • 284
  • 4
  • 15
  • 2
    You're missing that the file format doesn't store plain pixel-values. Try to read/write a `bmp` and you'll see that it takes roughly width*height*3 bytes (plus some overhead for the header) – tkausl Oct 17 '16 at 16:13

2 Answers2

1

You are right if each pixel consumes exactly one byte for storage in the image format. It is not the case actually.

Different file formats have different storage cost for a pixel.

For a pure black and white (not grayscale) image, every pixel need only a bit.

In PNG images with transparency, In addition to Red,Green and Blue components each pixel contains alpha component (transparency/opacity) too. So, number of bytes in a representation of an image depends on the image format and compression.

BufferedImage class lets you manipulate any pixel by its position.

try {
  BufferedImage img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}

You can use getRGB(int x, int y) and setRGB(int x, int y) methods to get or set specified pixel.

Mohammed Shareef C
  • 3,829
  • 25
  • 35
0

length < width * height can only happen if your image is binary, so if the type is TYPE_BYTE_BINARY. In that case, the encoding/storage is done line by line, and the number of byte element in your image is then [width/8 + min(width%8, 1) ] * height.

It can be superior in case of images with multiple channels/bands, so color images.

Before to convert an image into a ByteArrayOutputStream, make sure the image is encoded using Byte.

FiReTiTi
  • 5,597
  • 12
  • 30
  • 58