Friday, September 25, 2009

Java - extracting rgb values from an image

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
 
public class Main {
    public static void main(String[] args) {
        BufferedImage bimg = null;
        String input = "test.jpg";
        try{
            bimg = ImageIO.read(new File(input));
        }
        catch (Exception e) {
            // the test.jpg must be in the working dir  
            System.out.println(input + " is not in working dir");
        }
 
        System.out.println("height: " + Integer.toString(bimg.getHeight()));
        System.out.println("width: " + Integer.toString(bimg.getWidth()));
 
        // collect the rgb information 
        // regarding a single pixel 
        int rgb = bimg.getRGB(10, 10);
 
        // for some smart reason (that is beyond me) 
        // getting the rgb gives you a single int 
        // 
        // each component of colr occupies 8 bits 
        // this extracts the actual alpha, red, green, blue 
        int a = (rgb >>> 24) & 0xFF;
        int r = (rgb >>> 16) & 0xFF;
        int g = (rgb >>> 8) & 0xFF;
        int b = (rgb >>> 0) & 0xFF;
 
        // here is the proof 
        System.out.println("a: " + Integer.toString(a));
        System.out.println("r: " + Integer.toString(r));
        System.out.println("g: " + Integer.toString(g));
        System.out.println("b: " + Integer.toString(b));
 
        // this scripts output: 
        /* 
            height: 564 
            width: 634 
            a: 255 
            r: 222 
            g: 128 
            b: 184 
        */ 
    }
 
}
 
 

No comments:

Post a Comment