Monday, October 8, 2012

How to extract binary RGB raw pixel data in image formats in Java(jpg/gif/tif/png etc)?

So you want to extract the binary RGB pixels values from jpeg image format?

Let us assume that a pixel is composed of RGB values and all images are rectangular. Pixels are arranged in rows and columns. For a color image each pixel will have 3 components(RGB). It is exactly like channels in Photoshop. Now using the code below you can extract a component (R/G or B) from a color pixel and write it in individual file. This file will be black & while since it contains single color and has the same dimensions to that of original input image.

You can use any image format, just replace the file name in ImageIO.read and also each color file will be output in current directory as 1.out,2.out and 3.out. In these each pixel will be composed of single by(8 bits). It is unformatted raw image data.


/* * To change this template, choose Tools | Templates * and open the template in the editor. */

/** * * @author D14 */ import java.awt.image.*; import java.io.*; import java.util.*; import java.awt.image. BufferedImage; import java.io.File; import javax.imageio.ImageIO; class NewClass { public static void main(String args[]) { System.out.println("hello"); BufferedImage img = null; try { img = ImageIO.read(new File("F:/tmp/IMG_3955.JPG")); writeColorImageValueToFile(img); } catch (Exception e) { } }

public static void writeColorImageValueToFile(BufferedImage in) { int width = in.getWidth(); int height = in.getHeight();

System.out.println("width="+width+" height="+height); try { FileOutputStream fstream1 = new FileOutputStream("1.out"); FileOutputStream fstream2 = new FileOutputStream("2.out"); FileOutputStream fstream3 = new FileOutputStream("3.out"); byte [] b = new byte[width * height]; byte [] c = new byte[width * height]; byte [] d = new byte[width * height];

int [] data = new int[width * height]; in.getRGB(0, 0, width, height, data, 0, width); int min=0; int max=30;

for(int i = 0; i < (height * width); i++) { b[i]=(byte)((data[i] >> 16) & 0xff); c[i]=(byte)((data[i] >> 8) & 0xff); d[i]=(byte)(data[i] & 0xff); } fstream1.write(b); fstream2.write(c); fstream3.write(d);

} catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } }

No comments:

Post a Comment