Forum Stats

  • 3,852,528 Users
  • 2,264,112 Discussions
  • 7,905,094 Comments

Discussions

access bytes in BufferedImage.TYPE_BYTE_BINARY

am missing something obvious and was hoping someone could enlighten me ... i create a BufferedImage and i access the byte[] via ((DataBufferByte)inBuffImg.getRaster().getDataBuffer()).getData();

BufferedImage bimage = new BufferedImage(10,10,BufferedImage.TYPE_BYTE_GRAY);

gives me a byte[].length of 100 and i can access each individual pixel's gray value with & 0xFF

BufferedImage bimage = new BufferedImage(10,10,BufferedImage.TYPE_4BYTE_ABGR);

gives me a byte[].length of 400 and i can access each individual pixel's a b g and r values with & 0xFF ... all good so far ...

PROBLEM:

BufferedImage bimage = new BufferedImage(10,10,BufferedImage.TYPE_BYTE_BINARY);

gives me a byte[].length of 20 and i can't figure out how to access each individual pixel's 0,1 values from the byte array? (I know how to do this via getRGB() but this is too slow for my use here). any help greatly appreciated. thanks robert

update:

oh ... looks like padding causing the mismatch?

BufferedImage bimage = new BufferedImage(8,10,BufferedImage.TYPE_BYTE_BINARY);

gives byte[].length 10

that makes sense ... each pixel is now exactly a bit without padding because the width of the image is divisible by 8

BufferedImage bimage = new BufferedImage(9,10,BufferedImage.TYPE_BYTE_BINARY);

gives byte[].length 20

all the way up to

BufferedImage bimage = new BufferedImage(16,10,BufferedImage.TYPE_BYTE_BINARY);

gives byte[].length 20

i assume each new row of pixels starts with a bit at bit  zero. and end of each line padded to complete 8 bit boundary.

Best Answer

  • 4c3880db-960a-4cd4-9bc7-412ae46c86f2
    edited Apr 8, 2017 4:07PM Answer ✓

    looks like this strategy might get me there ... first need to know the number of bytes per row for the inBuffImg with ...

        int bytesPerRow = inBuffImg.getWidth()/8;

        if (inBuffImg.getWidth()%8>0)

            bytesPerRow+=1;

    then i get bit and byte positions with

        int bytePos = y*bytesPerRow + x/8;

        int bitPos = x%8;

    then i get the bit value

        pixels = ((DataBufferByte)inBuffImg.getRaster().getDataBuffer()).getData();

        return (pixels[bytePos] >> bitPos) & 1;

Answers

  • 4c3880db-960a-4cd4-9bc7-412ae46c86f2
    edited Apr 8, 2017 4:07PM Answer ✓

    looks like this strategy might get me there ... first need to know the number of bytes per row for the inBuffImg with ...

        int bytesPerRow = inBuffImg.getWidth()/8;

        if (inBuffImg.getWidth()%8>0)

            bytesPerRow+=1;

    then i get bit and byte positions with

        int bytePos = y*bytesPerRow + x/8;

        int bitPos = x%8;

    then i get the bit value

        pixels = ((DataBufferByte)inBuffImg.getRaster().getDataBuffer()).getData();

        return (pixels[bytePos] >> bitPos) & 1;

This discussion has been closed.