Grayscale value of a pixel in an image

Hi all,
I have an image . I want to read the image and find out its grayscale value of each pixel.
I have carried out several methods and used variety of classes to get the value of each pixel but all my effort went in vain.
It would be great if someone could write it for me from scratch.
Regards.

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GrayReader extends JPanel
    BufferedImage image;
    BufferedImage grayImage;
    JLabel label;
    JLabel red;
    JLabel green;
    JLabel blue;
    JLabel gray;
    public void showPixel(Point p)
        int rgb = image.getRGB(p.x, p.y);
        int r = (rgb >> 16) & 0xff;
        int g = (rgb >>  8) & 0xff;
        int b = (rgb >>  0) & 0xff;
        int grgb = grayImage.getRGB(p.x, p.y);
        int gVal = grgb & 0xff;
        red.setText(String.valueOf(r));
        green.setText(String.valueOf(g));
        blue.setText(String.valueOf(b));
        gray.setText(String.valueOf(gVal));
    private JPanel getImagePanel(MouseMotionListener l)
        label = new JLabel();
        label.addMouseMotionListener(l);
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10,10,10,10);
        panel.add(label, gbc);
        return panel;
    private JPanel getUIPanel(final Frame f)
        // row 1
        red = new JLabel(" ");
        green = new JLabel(" ");
        blue = new JLabel(" ");
        gray = new JLabel(" ");
        Dimension d = red.getPreferredSize();
        d.width = 45;
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        gbc.weightx = 1.0;
        JPanel row1 = new JPanel(gridbag);
        addComponents(new JLabel("r:"),    red,   row1, gbc, d);
        addComponents(new JLabel("g:"),    green, row1, gbc, d);
        addComponents(new JLabel("b:"),    blue,  row1, gbc, d);
        addComponents(new JLabel("gray:"), gray,  row1, gbc, d);
        // row 2
        JButton open = new JButton("open");
        open.addActionListener(new ActionListener()
            JFileChooser fileChooser = new JFileChooser("images");
            public void actionPerformed(ActionEvent e)
                if(fileChooser.showOpenDialog(f) == JFileChooser.APPROVE_OPTION)
                    File file = fileChooser.getSelectedFile();
                    try
                        image = ImageIO.read(file);
                    catch(IOException ioe)
                        System.out.printf("read error: " + ioe.getMessage());
                    // make a gray image to read pixels from
                    grayImage = new BufferedImage(image.getWidth(),
                                                  image.getHeight(),
                                                  BufferedImage.TYPE_BYTE_GRAY);
                    Graphics2D g2 = grayImage.createGraphics();
                    g2.drawRenderedImage(image, null);
                    g2.dispose();
                    // update gui
                    label.setIcon(new ImageIcon(image));
                    revalidate();
                    repaint();
        JPanel row2 = new JPanel();
        row2.add(open);
        JPanel panel = new JPanel(gridbag);
        gbc.insets = new Insets(0,0,0,0);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        panel.add(row1, gbc);
        panel.add(row2, gbc);
        return panel;
    private void addComponents(Component c1, Component c2, Container c,
                               GridBagConstraints gbc, Dimension d)
        gbc.anchor = GridBagConstraints.EAST;
        c.add(c1, gbc);
        c2.setPreferredSize(d);
        gbc.anchor = GridBagConstraints.WEST;
        c.add(c2, gbc);
    public static void main(String[] args)
        GrayReader grayReader = new GrayReader();
        PixelRanger ranger = new PixelRanger(grayReader);
        JPanel imagePanel = grayReader.getImagePanel(ranger);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(imagePanel));
        f.getContentPane().add(grayReader.getUIPanel(f), "Last");
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class PixelRanger extends MouseMotionAdapter
    GrayReader grayReader;
    public PixelRanger(GrayReader gr)
        grayReader = gr;
    public void mouseMoved(MouseEvent e)
        grayReader.showPixel(e.getPoint());
}

Similar Messages

  • How do you tell the color value of a pixel in an image data

    Hi,
    Given a BufferedImage of type, say BufferedImage.TYPE_4BYTE_ABGR, how do you tell the color value of a pixel in the image?
    Specifically, in the following code:
    Raster imgData = image.getData();
    int x = imgData.getMinX();
    int y = imgData.getMinY();
    int width = imgData.getWidth();
    int height = imgData.getHeight();
    I want to search the raster looking for a specific color, e.g., Color.WHITE.
    According to the API, "getSample()" may be used for this purpose. But, how do you know which color band a band index parameter in getSample() refers to? Does band index of 0 always refer to the RED band? Does band index of 1 refer to the GREEN band? etc.
    I'd greatly appreciate any help you may be able to provide.
    Thanks,
    --HS                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    In the print dialog underneath the settings for number of copies and print range you should see a dropdown menu probably called Layout. If you don't see that look for a button labeled Details and click it.
    Under the Layout menu you should find an option labeled Printer where you will find Printer specific options. Look for something there. You might also find an option called Color which may have options you are looking for.
    If this doesn't help, go to the printer manufacturer's website and look for answers there.

  • Grabbing Pixels from an image into an array

    Hi,
    I am new to the image processing using java. I want to get the pixel values of an image and store it into an text file. Can anyone help me with this?
    This is what i've done yet? Is the values present in the text field the correct values of the pixels of the image.
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.util.*;
    public class grabber extends Applet {
    private TextField tf;
    private TextArea ta;
    private Label status;
    private Canvas drawarea;
    private Image img=null;
    int ppmline=0;
    public void init() {
         setLayout(new GridLayout(1,2));
         Panel left=new Panel();
    left.setLayout(new BorderLayout());
    Panel topleft = new Panel();
    topleft.setLayout(new GridLayout(1, 4));
    topleft.add(tf=new TextField());
         Panel buttonsP = new Panel();
    buttonsP.add(new Button("Load GIF"));
         buttonsP.add(new Button("PPM Output"));
         topleft.add(buttonsP);
    left.add("North", topleft);
    left.add("Center", drawarea=new Canvas());
         left.add("South", status=new Label());
         add(left);               // left side of the applet.
         add(ta=new TextArea());          // right side.
         status.setText("See GIF files below.");
    public void paint(Graphics appletg) {
         Graphics g=drawarea.getGraphics();
         if (img != null) {
              g.drawImage(img, 0, 0, this);
              g.dispose();
    public boolean action(Event evt, Object arg) {
         String s=(String) arg;
         if(s.equals("Load GIF")) {
              img=getImage(getCodeBase(), tf.getText());
              repaint();
         else if (s.equals("PPM Output")) getPixs();
    return true;
    void getPixs() {
         int w=30, h=30;
         // PPM output starts.
         ta.setText("P3\n");
         ta.appendText(Integer.toString(w) + " " + Integer.toString(h) + "\n");
         ta.appendText("255\n");
         handlepixels(img, 0, 0, w, h);
    public void handlesinglepixel(int x, int y, int pixel) {
         // pixel is in RGB model. It is a 4-byte long integer.
         // It is converted into the string representation of PPM pixels.
         // ie. Hex 0x00102030 becomes "16 32 48"
         String s= Integer.toString((pixel & 0x00FF0000) >> 16) + " "
              + Integer.toString((pixel & 0x0000FF00) >> 8) + " "
              + Integer.toString(pixel & 0x000000FF) + " ";
    // If we use PPM RAW format, then we have to use ascii characters instead.
    //     char c[]= {(char) ((pixel & 0x00FF0000) >> 16),
    //          (char) ((pixel & 0x0000FF00) >> 8) ,
    //          (char) (pixel & 0x000000FF) };
    //     String s=new String(c);
         if (ppmline++>=3) {                // comment out if you use RAW format.
              ta.appendText(s + "\n");      // comment out if you use RAW format.
              ppmline=0;               // comment out if you use RAW format.
         } else                          // comment out if you use RAW format.
              ta.appendText(s);
    public void handlepixels(Image img, int x, int y, int w, int h) {
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
    try {
    pg.grabPixels();
    } catch (InterruptedException e) {
    System.err.println("interrupted waiting for pixels!");
    return;
    if ((pg.status() & ImageObserver.ABORT) != 0) {
    System.err.println("image fetch aborted or errored");
    return;
    for (int j = 0; j < h; j++) {
    for (int i = 0; i < w; i++) {
    handlesinglepixel(x+i, y+j, pixels[j * w + i]);

    im not at home or id post some source code but first off
    if your going to write a file from a applet your going to
    have to get by permisions.
    so you should probably do this with a application
    it would be alot easier
    use toolkit.getdefaulttoolkit() to get the image then
    use the pixel graber class to read it into a array
    of the type you want string or char
    then just write it into a file each element of the array
    and when you want to read it just read it in with file reader
    you could probaly do a test run just write in each value as
    a string and put a comma between each value then use
    stringtokenizer to read it back in its less efficient but
    for a test run it would make things clearer
    sorry if its not much help

  • Reading grayscale values from saved image

    Hi,
    I've written several methods that crop, convert to grayscale, histogram equalise and then resize a colour jpeg image for preparing sets of images for a face detection neural network. The next thing I want to do is to write a method that allows me to read that saved grayscale images pixel values back as singular grayscale values from the RGB values that were used to save the jpeg. I used this code to create the 2D array of grayscale pixel values
          for (int i = 0; i < imageWidth; i++)
                for (int j=0; j <imageHeight; j++)
                    grayRGB[i][j] = (rgb[i][j] & 0xff000000) | (eqGray[i][j]<<16) | (eqGray[i][j]<<8) | (eqGray[i][j]);
                    img.setRGB(i, j, grayRGB[i][j]);
                }and then used this code to resize the image:
            BufferedImage resized = new BufferedImage(20,20,1);
            Graphics2D g = resized.createGraphics();
            g.drawImage(img, 0, 0, 20, 20, null);
            g.dispose();my class gets the RGB values on instantiation as follows:
            //get RGB pixel values for image loaded
            for (int i = 0; i < imageWidth; i++)
                for (int j=0; j <imageHeight; j++)
                    rgb[i][j]= inputImage.getRGB(i,j);
                    //perform bitwise shift rgb information values to obtain appropriate values for each colour pixel
                    r[i][j]=  (rgb[i][j] >> 16) &0xff;
                    g[i][j]=  (rgb[i][j] >> 8) &0xff;
                    b[i][j]=  (rgb[i][j]) &0xff;
                }Is there a way to get the grayscale values directly from an image that is already converted to grayscale without having to perform the grayscale conversion method again, perhaps using a similar bitwise shift?
    Thanks
    Nick

    answering this myself for those lost souls like i was a while ago:
    the answer is very simple when you get to know it :) : use a signed type for your image. this can be achieved by using the Format Operator (javax.media.jai.operator.FormatDescriptor). an example as follows :
            BufferedImage bufferedImage= someimage...
            ParameterBlock pb = new ParameterBlock();
            pb.addSource(bufferedImage);
            pb.add(DataBuffer.TYPE_SHORT);
            RenderedImage formattedImage =
                    JAI.create("format", pb, null);
    // you may use as well TYPE_DOUBLE or TYPE_FLOATimage could be of any type such as PlanarImage, BufferedImage, RenderedImage etc..
    then all you need to do is read your pixel values by using an iterator such as RectIter or RandomIter to access pixel values etc..
    San

  • Saving an image as a table of grayscale values?

    I have an image that is in grayscale and I need a table that displays each pixels grayscale value.  Is there a way to save the image in some tabular format or can I convert it any other way in photoshop?

    You have posed a reasonable question. The short answer is that Photoshop does not have a utility to provide the data you require as you would like it. The closest feature it has which may be of some use is the measurement facility in the Extended version of Photoshop.
    Using the measurement facility you can draw a selection around an area of your choosing (one of the rocks, for example) and take the measurement. It will provide you with several pieces of data including Gray value max, min, mean, median, integrated density and histogram. Area & perimeter of the selected area are also included and a few other parameters. All of these data including the numerical data of the histogram can be exported out of Photoshop to be used in a spreadsheet. If these data were useful, you could do a selection around the other rock and do a comparison.
    The raw data behind an image can be had from its psd file, but you need to know have some tools to digest that data.
    Paulo

  • How to get the RGB value of each pixel of a hole image?

    Hi,
    I'm trying the get the RGB(between 0 and 255) value of each pixel of a hole image. I writte this code:
    public void convertImage()
         int w = bufferedImage.getWidth();
         int h = bufferedImage.getHeight();
         int[] rgbs = new int[w*h];/* create a new array */
         bufferedImage.getRGB(0,0,w,h,rgbs,0,w);
         for(int i=0; i<10; i++)  
             System.out.println(rgbs);
    But the value rgbs[] contain an 8 bits integer, it's possible to have the RGB of this.
    In other case, do you have another sample of code to help me to get the RGB value of each pixel of a hole image?
    thanks.

    Hi, I am currently working on an application which requires the generation of color histograms that are a representation of a given image ie; myImage.jpg. I have made use of the JAI API and used it's Histogram class to generate a histogram vector for the image that I provide.
    However, upon closer inpsection, I have realised the following:-
    (1) The image, as it contains multiple colours is a multi-banded image ie; this means that each individual pixel in the image contains multiple colour samples (I assume) ie; Red, Blue Green. Due to this, a "separate list of bins represents each individual band". This means that for myImage.jpg, there is not ONE individual vector that contains data such as "400 pixels purple" "5000 pixels yellow" etc but there are indeed 3 vectors that represent the image.
    I have found this to be true using the getBinSize(int band, int bin) method call - the first parameter being 0,1,2 for Red Blue or Green.
    My basic (or complex) problem is that I basically want to generate 2 color histogram vectors that represent 2 separate images and then compare these vectors "side-by-side" using the vector comparison algorithms that I have already developed.
    Is there a way of using Java's Histogram class and it's associated methods to be able to store all colour information for an image in only ONE vector?? I am pretty certain that this is not possible, so my dilemma is now: - If I have an image and it is represented by three separate vectors/histograms, then how can I possibly compare these to say whether an image matches or not.
    When a pixel is analysed by a program, what seems to be the result returned is how that pixel is made up in terms of Red, Green or blue ie; a purple pixel is X blue, X red and X green and hence 3 vectos existing.
    Can anybody offer advice on how to achieve this task of looking at a pixel and simply determining it's actual color. I would preferably like to keep my code that I have already developed ie; the use of the Java Histoogram class but any other offerings are appreciated.

  • Find out and get the bit value for each pixel in image

    i use 16bit image. the image is 200x200 pixels. i need to know what is
    the bit value for each pixel. example(0111111011111101).
    where i can see the bit value output. if somebody got the example surce code please send it to me.coz i need the bit value to find out how many RGB color that use in the image. thanks for ur help.

    How many logins do you have???

  • How can I get to read the pixels in an image?

    Please see details of my code below. What I am doing is trying to obtain the pixels for an image. there is an initial image of a certain size, which is then split into smaller portions.
    The problem I'm getting is that pixels can not be read past the middle of the original image. I hope I have explained this so it can be understood. I have included the class that I am working on
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package MandelbrotConstruction.compression;
    import java.awt.*;
    import java.awt.color.ColorSpace;
    import java.awt.geom.AffineTransform;
    import java.awt.image.*;
    import java.io.*;
    import java.util.ArrayList;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    * @author Charlene Hunter
    public class DisplayImg extends JPanel {
        private static BufferedImage image;
        private static ArrayList<Range> rangeLot;
        private static ArrayList<Domain> domainLot;
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            int w = MainFrame.getJPanel1().getWidth();
            int h = MainFrame.getJPanel1().getHeight();
            Graphics2D g2 = (Graphics2D) g;
            File img = MainFrame.getImgFile();
            image = null;
            if (img != null) {
                try {
                    image = ImageIO.read(img);
                    //filter the image with a grayscale
                    ColorConvertOp grayOp = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
                    image = grayOp.filter(image, null);
                    //scale image to the size of the panel
                    AffineTransform at = new AffineTransform();
                    at.scale(256.0 / image.getWidth(), 256.0 / image.getHeight());
                    AffineTransformOp resizeOp = new AffineTransformOp(at, null);
                    image = resizeOp.filter(image, null);
                    ArrayList<Range> r = createRanges(image, 3);
                    ArrayList<Domain> d = createDomains(image);
                    int i = 0;
                    for (Domain dom : d) {
                        System.err.println("this is " + i);
                        System.out.println(dom.getPixels());
                        i++;
                    CompareClass comparer = new CompareClass(r, d);
                } catch (IOException e) {
                    System.err.println("IOException");
            g2.drawImage(image, null, 0, 0);
        public static ArrayList<Range> createRanges(BufferedImage bi, int divisions) {
            int w = bi.getWidth();
            int h = bi.getHeight();
            rangeLot = new ArrayList<Range>();
            int k = (int) Math.pow(2, divisions);
            for (int x = 0; x < w; x = x + (w / k)) {
                for (int y = 0; y < h; y = y + (h / k)) {
                    BufferedImage range = bi.getSubimage(x, y, w / k, h / k);
                    double[] pix = range.getRaster().getPixels(x, y, range.getWidth(), range.getHeight(), (double[]) null);
                    Range r = new Range(x, y, range, pix);
                    rangeLot.add(r);
            return rangeLot;
        public static ArrayList<Domain> createDomains(BufferedImage bi) {
            int w = bi.getWidth();
            int h = bi.getHeight();
            domainLot = new ArrayList<Domain>();
            int step = 4;
            for (int x = 0; x < w - step; x = x + step) {
                for (int y = 0; y < h - step; y = y + step) {
                    BufferedImage domain = bi.getSubimage(x, y, 2 * step, 2 * step);
                    double[] pix = domain.getRaster().getPixels(x, y, domain.getWidth(), domain.getHeight(), (double[]) null);
                    Domain d = new Domain(x, y, domain, pix);
                    domainLot.add(d);
            return domainLot;
    }If what I have included is not sufficient, please let me know. the problem is only arising when the pixels are being obtained for the subimage
    Thanks

    Hi, the error message I am getting is (i'm printing out the x,y values and width and height so that I can see what going on) the whole image is 512x512, and I am grabbing pixels for squares of 64x64, but when it gets to 256 it throws an exception. I don'd understand why
    (x: 0, y: 0)
    width: 64, height: 64
    done!
    (x: 0, y: 64)
    width: 64, height: 64
    done!
    (x: 0, y: 128)
    width: 64, height: 64
    done!
    (x: 0, y: 192)
    width: 64, height: 64
    done!
    (x: 0, y: 256)
    width: 64, height: 64
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
            at java.awt.image.ComponentSampleModel.getSampleDouble(ComponentSampleModel.java:807)
            at java.awt.image.SampleModel.getPixels(SampleModel.java:823)
            at java.awt.image.Raster.getPixels(Raster.java:1613)
            at MandelbrotConstruction.compression.DisplayImg.createRanges(DisplayImg.java:83)
            at MandelbrotConstruction.compression.DisplayImg.paintComponent(DisplayImg.java:51)
            at javax.swing.JComponent.paint(JComponent.java:1006)
            at javax.swing.JComponent.paintChildren(JComponent.java:843)
            at javax.swing.JComponent.paint(JComponent.java:1015)
            at javax.swing.JComponent.paintChildren(JComponent.java:843)
            at javax.swing.JComponent.paint(JComponent.java:1015)
            at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
            at javax.swing.JComponent.paintChildren(JComponent.java:843)
            at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4979)
            at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4925)
            at javax.swing.JComponent.paint(JComponent.java:996)
            at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
            at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
            at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
            at java.awt.Container.paint(Container.java:1709)
            at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
            at sun.awt.RepaintArea.paint(RepaintArea.java:224)
            at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
            at java.awt.Component.dispatchEventImpl(Component.java:4060)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Window.dispatchEventImpl(Window.java:1791)
            at java.awt.Component.dispatchEvent(Component.java:3819)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

  • Numeric value of a pixel

    Hello,
    Is there any posibility to get the NUMERIC values of pixels of a grayscale image stored in a blob, where the value of each pixel is in 1 byte(256 shades of grey )?
    I triet to use g := DBMS_LOB.SUBSTR(pic, Amount , current_pos );
    where
    g raw(1);
    Amount int:=1;
    but it seems that there is no method which could convert raw byte into a number
    for every value of the byte.
    Could I somehow have the binary value of a raw variable and get the decimal number with some kind of shift and "binary AND" operation ?

    For this kind of stuff, you would be much better off using java stored procedures and JAI. We use JAI internally to do processing...
    It is not trivial, but it should be the best way.
    Larry

  • Getting pixels from an image

    I'm currently writing a Java3D-based renderer for terrain data. The rendering engine works great, and I've tested it with OS DEM files.
    I thought it would be neat to code a class similar to the one I use to parse DEM files, but that takes Jpeg images and specifies altitude from the brightness component of the HSB of each pixel. This is where the problem begins.
    I (naively) thought it would be a simple case of getting the image with something like
    Image image = Toolkit.getDefaultToolkit().getImage(fname);
    Then using a getColor(x,y) or similar method to get the data out of the image. Only it doesn't seem to be so simple. It looks like I need to use a BufferedImage, which in turn wants a Raster, which wants two other classes.... and the whole thing gets complicated.
    If anyone knows a quick (hoping it's a 3 or 4 line thing) way to set up an object that can be readily accessed to read the HSB value of each pixel (ideally by returning it as an awt.Color class), I'd really appreciate it. Or a link to a good tutorial on the subject.
    Thanks.

    Thanks :) Knew it should be simpler than it looked :)

  • Get the color of a pixel in an image

    how can i do to get the color of a pixel in an image ???
    Can anyone help me ?

    Hi,
    first of all you need to get the library to transfer your image to java.awt.image.BufferedImage object.
    I know many such libraries. Its depends of what kind of image you have: jpeg, gif, png or other.
    And when you get the BufferedImage of you picture using library, then you can get the color of any pixel in image using int BufferedImage.getRGB(int x, int y) as integer value.
    Victor Letunovsky

  • Looking for the brighter red pixel of an image

    Hi, I need to find the brighter red pixel of an image. I tried this code, but the value of each pixel seemed to be the same (zero).
    public static void findBrighterRedPoint(Image i, ImageObserver o){
         int redMax = 0; //0 to 255
         int xMax = 0;
         int yMax = 0;
         PixelGrabber pg = new PixelGrabber(i,0,0,i.getWidth(o),i.getHeight(o),true);
         ColorModel cm = pg.getColorModel();
         for(int a=0;a<pg.getHeight();a++){
              for(int c=0;c<pg.getWidth();c++){
                   if(cm.getRed(((a-1)*pg.getWidth()+c)) > redMax){
                        redMax = cm.getRed(((a-1)*pg.getWidth()+c));
                        xMax=c;
                        yMax=a;
                   if(f==(pg.getHeight()-1) && c==(pg.getWidth()-1)){
                   System.out.println("Red bound max value: "+cm.getRed(((a-1)*pg.getWidth()+c))+" Arrow: "+a+" Collumn: "+c);
    }//method endThanks for some help...
    Edited by: juanma268 on Jul 25, 2008 5:45 PM

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class LookingForRed extends MouseMotionAdapter {
        JLabel red, green, blue;
        BufferedImage image;
        public void mouseMoved(MouseEvent e) {
            Point p = e.getPoint();
            int rgb = image.getRGB(p.x, p.y);
            red.setText(String.valueOf(  (rgb >> 16)&0xff));
            green.setText(String.valueOf((rgb >>  8)&0xff));
            blue.setText(String.valueOf( (rgb >>  0)&0xff));
        public static void findBrighterRedPoint(Image i, ImageObserver o){
            int redMax = 0; //0 to 255
            int xMax = 0;
            int yMax = 0;
            int w = i.getWidth(o);
            int h = i.getHeight(o);
            int[] pixels = new int[w*h];
            PixelGrabber pg = new PixelGrabber(i,0,0,w,h,pixels,0,w);
            try {
                pg.grabPixels();
            } catch(InterruptedException e) {
                System.out.println("interrupt");
            ColorModel cm = pg.getColorModel();
            for(int a=0;a<pg.getHeight();a++){
                for(int c=0;c<pg.getWidth();c++){
                    int index = a*pg.getWidth()+c;
                    int pixel = pixels[index];
                    if(cm.getRed(pixel) > redMax){
                        redMax = cm.getRed(pixel);
                        xMax=c;
                        yMax=a;
                    if(a==(pg.getHeight()-1) && c==(pg.getWidth()-1)){
                        System.out.println("Red bound max value: "+redMax+
                                   " Arrow: "+yMax+" Collumn: "+xMax);
        private void showGUI(BufferedImage image) {
            this.image = image;
            ImageIcon icon = new ImageIcon(image);
            JLabel label = new JLabel(icon, JLabel.CENTER);
            label.addMouseMotionListener(this);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(label, new GridBagConstraints());
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(panel);
            f.add(getLabelPanel(), "Last");
            f.setSize(300,300);
            f.setLocation(200,200);
            f.setVisible(true);
            findBrighterRedPoint(image, label);
        private JPanel getLabelPanel() {
            red = new JLabel();
            green = new JLabel();
            blue = new JLabel();
            Dimension d = new Dimension(45, 25);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents("r =", red,   panel, gbc, d);
            addComponents("g =", green, panel, gbc, d);
            addComponents("b =", blue,  panel, gbc, d);
            return panel;
        private void addComponents(String s, JLabel jl, Container c,
                                   GridBagConstraints gbc, Dimension d) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(new JLabel(s), gbc);
            jl.setPreferredSize(d);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(jl, gbc);
        public static void main(String[] args) {
            LookingForRed test = new LookingForRed();
            BufferedImage image = test.makeImage();
            test.showGUI(image);
        private BufferedImage makeImage() {
            int w = 200, h = 200;
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage image = new BufferedImage(w, h, type);
            int[] data = new int[w*h];
            int x = 3*w/4;
            int y = 3*h/4;
            System.out.println("Max red value should appear at " +
                               "x = " + x + "  y = " + y);
            int a = 255;
            for(int j = 0; j < h; j++) {
                int b = j*255/(h-1);
                for(int k = 0; k < w; k++) {
                    int r = (j == y && k == x) ? 255 : 127;
                    int g = k*255/(w-1);
                    data[j*w + k] = ((a & 0xff) << 24) |
                                    ((r & 0xff) << 16) |
                                    ((g & 0xff) <<  8) |
                                    ((b & 0xff) <<  0);
            image.setRGB(0,0,w,h,data,0,w);
            return image;
    }

  • Get bit value for each pixel.

    i use the 16bit image so i need to get the bit value for each pixel. hope someone knows it can help me. thanks.

    Get the BufferedImage Object and do a getData() on it . This returns a Raster object. The Raster Object has methods for retrieving the pixel information.
    hope this helps.

  • How to get the r,g,b value of a pixel in a picture

    Hi, there
    How can I get the integer value of the r, g, b value of a pixel in a picture. This picture is loaded from a file, such as jpg or gif. That means the absolute position of the left corner of the picture may be float when you change the size of the window.
    Thanks in advance.

    Hi, there
    I try the way that you suggested, but it still cannot work. I attach the fragment code here. If anyone have time, please help me to check why I always get 0 for the r,g and b value.
    Thanks in advance
    public class cc
    {   public static void main(String[] args)
    {   PFrame frame = new PFrame();
    frame.setTitle("Pixels");
    frame.setSize(200,200);
    frame.setBackground(Color.blue);
    frame.show();
    class PFrame extends JFrame implements ActionListener
    {   DrawPanel dp;
    JButton clickButton;
    JTextField rgbTextField;
    public PFrame()
    {   dp = new DrawPanel();
    clickButton = new JButton("Show RGB");
    clickButton.addActionListener(this);
    rgbTextField = new JTextField("RGB show here");
    Container contentPane = getContentPane();
    contentPane.add(clickButton, "North");
    contentPane.add(rgbTextField, "South");
    contentPane.add(dp, "Center");
    public void actionPerformed(ActionEvent ae)
    {   BufferedImage bi = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    int rgb = bi.getRGB(5,5);
    //int red = (rgb & 0xff0000) >> 16;
    //int green = (rgb & 0xff00) >> 8;
    //int blue = rgb & 0xff;
    int red = new Color(rgb).getRed();
    int green = new Color(rgb).getGreen();
    int blue = new Color(rgb).getBlue();
    rgbTextField.setText("Red = " + red + " Green = " + green + " Blue = " + blue);
    class DrawPanel extends JPanel
    {   public void paintComponent(Graphics g)
    {   super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setColor(new Color(10,20,39));
    g2.fillRect(0,0,10,10);
    g2.setColor(Color.red);
    g2.fillRect(60,60,20,20);

  • How do you reduce the pixels of an image to fit within certain requirements

    I am trying to get the pixels of an image to fit certain requirements. When I try to edit the image in iPhoto by clicking custom constrain and then enter the pixel of dimensions I want, it will not adjust the image to them. Does anyone know how I can do this?

    Select the pic in the iPhoto Window and go
    File -> Export
    in the resulting dialogue you can resize:
    Uploaded with plasq's Skitch!
    Regards
    TD

Maybe you are looking for