How to read a image in java and turn it to byte array?[use Lena.bmp 512x512 as example] -
i want analysis pixel of lena.bmp (matlab) don't know how in java , store byte[]
i have read aritle:
how convert image byte array in java?
but when implement, find some pixel value did't exist
. example , pixel range 0~255, can not find '120' on pixel of photo(lena.bmp).
there code
/* * change template, choose tools | templates * , open template in editor. */ package image_io; import java.awt.image.bufferedimage; import java.io.bytearrayoutputstream; import java.io.file; import java.io.ioexception; import javax.imageio.imageio; /** * * @author user */ public class readimage { public static void main (string []args){ byte[] imageinbyte; int [] kindofpixel = new int [256]; try{ bufferedimage originalimage = imageio.read(new file("c:\\users\\user\\desktop\\project\\lsb_implement\\lena.bmp")); bytearrayoutputstream baos = new bytearrayoutputstream(); imageio.write( originalimage, "bmp", baos ); baos.flush(); imageinbyte = baos.tobytearray(); system.out.println(imageinbyte.length); baos.close(); for(int i=0;i<imageinbyte.length;i++){ kindofpixel[imageinbyte[i]+128]++; //java byte defined -128~127 (+128)==> 0~256 } for(int i=0;i<kindofpixel.length;i++){ //show pixel color value system.out.println(i+" , "+kindofpixel[i]); } }catch(ioexception e){ system.out.println(e.getmessage()); } } }
i compare information histogram of lena.bmp , seems have different...
first on java byte
you aware signed java byte ranges -128 127. erred using 128 instead of calculating modulo 256:
that comes down to:
kindofpixel[imageinbyte[i] & 0xff]++;
to for:
- an unsigned byte 120: < 127 hence 120,
- an unsigned byte 130: >= 127 hence 130 - 256 = -126.
modulo 256 calculation in other direction goes:
byte signed = -126; int unsigned = signed < 0 ? signed + 256 : signed; int unsigned = signed & 0xff; // or
the pixels
a bmp file not (only) linearized list of pixels. 1 better use int[] bufferedinage.getrgb:
int[] pixels = originalimage.getrgb(0, 0, width, height, null, 0, width);
remains color representation
bmp knows many variants: rgb, indexed etcetera. indexed colors need lookup in palette.
Comments
Post a Comment