java - Manipulating pixels in binary bitmap image with DataBufferByte -


i'm having trouble accessing individual pixels in bufferedimage. image binary, in black or white only. means each byte of image contains 8 pixels (1 bit per pixel).

to make sure i'm indexing image correctly, wrote quick test set pixels 1 (black):

import javax.imageio.imageio; import java.awt.image.bufferedimage; import java.awt.image.databufferbyte; import java.io.file;  public class imagetest {     public static void main(string... args) throws exception {         file input = new file("stripes.bmp");         final bufferedimage image = imageio.read(input);         system.out.println(image);          byte[] byte_buffer = ((databufferbyte) image.getraster().getdatabuffer()).getdata();          final int width = image.getwidth(), height = image.getheight();          (int j = 0; j < height; j++) {             (int = 0; < width; i++) {                 int byte_index = (i + j * width) / 8;                 int bit_index = (i + j * width) % 8;                 byte_buffer[byte_index] |= 1 << bit_index;             }         }          imageio.write(image, "bmp", new file("stripes_out.bmp"));     } } 

the input image, stripes.bmp looks like: stripes.bmp

and output is: stripes_out.bmp

i expected image come out black, there few rows @ bottom weren't modified. apparently, i'm not reaching end of byte buffer.

investigating further, looks there bytes in array.

width = 810, height = 723 -> width * height / 8 = 73203 byte_buffer.length = 73746 

unfortunately, these 543 bytes aren't @ beginning, because skipping first 543 bytes leaves few rows unmodified @ beginning of image.

what missing? how can index individual pixels correctly?

each image row in byte buffer array byte-aligned. means "real" bit width of each row needs multiple of 8. in image, each row rounded 816 bits. assume last 6 bits in each row discarded.

    816 * 723 / 8 = 73746 

so round width nearest multiple of 8 , use in inner loop:

    final int width = image.getwidth(),               height = image.getheight(),               rowbitwidth = ((width + 7) / 8) * 8;      (int j = 0; j < height; j++) {         (int = 0; < width; i++) {             int byte_index = (i + j * rowbitwidth) / 8;             int bit_index = (i + j * rowbitwidth) % 8;             byte_buffer[byte_index] |= 1 << bit_index;         }     } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

javascript - addthis share facebook and google+ url -

ios - Show keyboard with UITextField in the input accessory view -