PixelGrabber

Hi all,
I'm using the method grabPixel of the class PixelGrabber to get an array of pixels of an image.
The problem is that the array I'm getting is not correct and the x right pixels(in my case 473 right pixels) in each line of the matrix of the image is shifted to the left part of that line and all of them get the value 0 (which is black).
How can I avoid this problem?
The following code is the code of the class using PixelGrabber:
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.awt.image.*;
public class FilePanel extends JPanel {
protected Image currentImage = null, modImg = null;
private boolean isFile = false;
private int pictureWidth, pictureHeight;
private int count = 0;
protected int[] pixels, pix;
private MediaTracker tracker;
private ColorModel colorModel;
public FilePanel() {
setBorder (BorderFactory.createTitledBorder("Picture Area:"));
tracker = new MediaTracker(this);
colorModel = ColorModel.getRGBdefault();
public void setFile(String fileName)
if (fileName != null)
currentImage=null;
isFile = true;
if (fileName.endsWith(".bmp") || fileName.endsWith(".BMP"))
BMP bmp = new BMP(new java.io.File(fileName));
currentImage = bmp.getImage();
else
Toolkit toolkit = Toolkit.getDefaultToolkit();
currentImage = toolkit.getImage(fileName);
try
tracker.addImage(currentImage,11);
tracker.waitForID(11);
catch(InterruptedException e)
e.printStackTrace();
System.err.println("*ERROR* MediaTracker rudely interrupted.");
currentImage=null;
tracker.removeImage(currentImage);
pictureWidth = currentImage.getWidth(this);
pictureHeight = currentImage.getHeight(this);
handlepixels(currentImage, (getWidth() - pictureWidth)/2 - 60, 0,
pictureWidth, pictureHeight);
isFile = true;
repaint();
public void paintComponent(Graphics g)
if (currentImage != null && currentImage.getHeight(null)>=0)
super.paintComponent(g);
g.drawImage(currentImage, (this.getWidth() - 300)/2,
(this.getHeight() - 90)/2, this);
public byte[] sendPixel (byte byteArray[])
int numOfBits = 8, numOfBytesInLine = pictureWidth/8,
numOfLines = pictureHeight, countPixels = 0, gray,
currentPixel, bit = -1;
byte currentByte = 0;
int j = 0;
if (currentImage == null)
System.out.println("Picture has not been loaded yet");
return null;
else
for (int i = 0 ;i < pixels.length; i++)
currentPixel = manipulatePixel(pixels);
if (currentPixel > 128)
currentByte &= 0xfe;
else
currentByte |= 0x01;
bit++;
if (bit != 7)
currentByte <<= 1;
else
bit = -1;
byteArray[i/8] = currentByte;
currentByte = 0;
return byteArray;
public int manipulatePixel (int pixel)
return ((pixel&0xff)+((pixel&0xff00)>>8)+((pixel&0xff0000)>>16))/3;
public void handlepixels(Image img, int x, int y, int w, int h) {
System.out.println("w "+w+" h "+h);
pixels = new int[w * h];
int red, green, blue;
     PixelGrabber pg = new PixelGrabber (img, x, y, w, h, pixels, 0, w);
     try {
     if (pg.grabPixels()&&((pg.getStatus() & ImageObserver.ALLBITS) != 0))
else
System.out.println("Did not succeed to grab pixles");
catch (InterruptedException e) {
     System.err.println("interrupted waiting for pixels!");
     return;
repaint();
public int getNumOfLines () {return pictureHeight;}
public int getNumOfBytesInLine () {return pictureWidth/8;}
Thanks,
gabi

Method is somethig like this:
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)
          for (int j = 0; j < h; j++)
for (int i = 0; i < w; i++)
               //what do I need to do inside this loop?
     // Ineed to check pixel by pixel if it is certain color and then convert it to
               //different color.     
               Image new_image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, image, 0, w));
     }

Similar Messages

  • PB: PixelGrabber, offscreen Image, Windows 98, ie5

    Hello,
    I've got a problem with a bug that occurs under Windows 98, and ie5.
    This is the code of a little applet that works fine under Windows NT, but not under Windows 98:
    This applet draws 3 colors in a square, and use the grabPixel method for catching the pixels of the image and create another image with those pixels.(the image should be the same)
    The problem is that the grabPixel method changes the colors of the pixels. It occurs only with an offscreen Image (that means an Image created with the createImage(w, h) method). there is no problem with a MemoryImageSource, for example.
    I just notice that the ColorModel of an offscreen Image is not the same as the default ColorModel:
    colorModel: java.awt.image.DirectColorModel = {...}
    red_mask: int = 0xf800 (instead of 0x00ff0000 )
    green_mask: int = 0x7e0 (instead of 0x0000ff00 )
    blue_mask: int = 0x1f (instead of 0x000000ff)
    alpha_mask: int = 0x0 (instead of 0xff000000)
    red_offset: int = 0xb
    green_offset: int = 0x5
    blue_offset: int = 0x0
    alpha_offset: int = 0x0
    red_scale: int = 0x1f
    green_scale: int = 0x3f
    blue_scale: int = 0x1f
    alpha_scale: int = 0x0
    But i don't know how to solve the bug.
    Here is the code :
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    public class AppletFlush extends Applet implements Runnable{
    Thread anim;
    Image memimg;
    boolean bool;
    Image offImage;
    Graphics offGraphics;
         public void init() {
         public void start() {
         anim = new Thread(this);
         anim.start();
    bool = true;
    offImage = this.createImage(100, 100);
    offGraphics = offImage.getGraphics();
         public synchronized void stop() {
         anim = null;
         notify();
         public synchronized void run() {
         while (Thread.currentThread() == anim) {
    int[] pixels = new int[100 * 100];
    int color = 0;
    //set the pixels of a squared image that contains 3 colors (this is my reference image)
    if (bool)
    bool = false;
    for (int i=0; i<100; i++)
    if (i<33)
    color = 0xffff0000;
    else if (i<66)
    color = 0xff00ff00;
    else
    color = 0xff0000ff;
    for (int j=0; j<100; j++)
    pixels[i*100 + j] = color;
    else
    //grab the pixels of the offscreen image(here is the problem)
    PixelGrabber pg = new PixelGrabber(offImage, 0, 0, 100, 100, pixels, 0, 100);
    try
    pg.grabPixels();
    catch (InterruptedException ex)
    System.out.println("erreur pendant gragPixels !!!");
    //create the new image with the pixels
    MemoryImageSource imgsrc = new MemoryImageSource(100, 100, pixels, 0, 100);
    memimg = createImage(imgsrc);
    //draw the image in the offscreen image
    offGraphics.drawImage(memimg, 0, 0, null);
              repaint();
              try {wait(1000);} catch (InterruptedException e) {return;}
         public void paint(Graphics g) {
         // display the offscreen image
         g.drawImage(offImage, 0, 0, this);
    PLEASE HELP !
    YaYa

    try
    public void paint(Graphics g )
    if((_offScreen != null)&&(offScreenImage != null))
    // put your stuff here
    else
    update(g);
    g.dispose();
    g.finalize();
    return;
    public void update(Graphics g)
    if( offScreenImage == null)
    offScreenImage = this.createImage( width, height );
    if( _offScreen == null)
    _offScreen = offScreenImage .getGraphics();
    paint(g);
    }

  • How does pixelgrabber store the pixels?

    i used pixelgrabber like so in an applet
    Image ball = getImage(getCodeBase(), "bball.gif");
    int w = ball.getWidth(this);
    int h = ball.getHeight(this);
    int[] pixels = new int[w * h];
    PixelGrabber pg=new PixelGrabber(ball,0,0,w,h,pixels,0,w);
    try{
    pg.grabPixels();
    }catch (InterruptedException e) {}
    when i go used a for loop to print out all the elements of pixels[] 1 by 1, i get something like this.
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -2697514
    -2697514
    -4868683
    -5395027
    -8684677
    -8684677
    -5921371
    -5395027
    -3223858
    -2697514
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    -1
    now, this basketball image is fills up most of the 64x64 space, its mostly orange with black borders (as you would expect). but why do i get so many -1's (-1 is FFFFFFFF, which is white)?

    From the PixelGrabber docs:
      int alpha = (pixel >> 24) & 0xff;
      int red   = (pixel >> 16) & 0xff;
      int green = (pixel >>  8) & 0xff;
      int blue  = (pixel      ) & 0xff;I've used this in code that slices an image into a 10x10 grid and
    figures out the "main color" in each cell. Do it twice, compare
    the result and you can tell if Image A is a scaled version of Image B.
    Given that my code works, I'd have to say that the storage described
    here is accurate !
    Hope this helps !

  • PixelGrabber is too slow and has memory problems!

    Have any of you figured out a way to get pixels from an Image
    WITHOUT using PixelGrabber??
    PixelGrabber is really slow -- is a memory hog -- and has other problems
    that cause me to need another way to get pixels from an image.
    Does anyone else have a way to get the pixels directly from an Image
    without using PixelGrabber?
    Ken Warner

    Hi, there are ways to do it if you can live with certain restrictions.
                BufferedImage img=new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
                img.setRGB(10,15,0x01020304);   // a=1 r=2 g=3 b=4
                WritableRaster r=img.getRaster();
                DataBuffer db=r.getDataBuffer();
                if (db.getDataType() != DataBuffer.TYPE_INT)
                    throw new IllegalStateException("Hey that must be a int!");
                if (db.getNumBanks() != 1)
                    throw new IllegalStateException("Uh - Someone else got to do this job!");
                DataBufferInt dbi=(DataBufferInt)db;
                int[] data=dbi.getData();           
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));
                // Test: No coy
                data[10+32*15]=0xaabbccdd;
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));As you see it works best if you can set the pixel format and if it only contains a single array of data (i.e. bank).

  • Error with PixelGrabber

    I am following some code on face recognition. I have my main class which is pretty straight forward
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FR extends JFrame {
           static Image[] trainingImages;
           static Image[] EigenImages;
           static Image[] diffImages;
          static image trainingSet;
          static Image averageImage;
          static display draw;
          static String testImage ="testImages/anita3.GIF";
           static int w;
          public FR(String s)
                 super(s);
                 trainingSet = new image("TrainingPics",this);
             draw = new display();
                 this.w=trainingSet.w;
    public static void main(String s[]) {
             FR frame = new FR("Face Recognition");
             trainingImages = draw.drawBehind(trainingSet.TrainingImageVector,trainingSet.w,trainingSet.h);
             averageImage = draw.arrayToImage(trainingSet.averageImage ,trainingSet.w,trainingSet.h);
             diffImages = draw.drawBehind(trainingSet.diffImageVector,trainingSet.w,trainingSet.h);
             EigenImages = draw.drawBehind(trainingSet.EigenVector,trainingSet.w,trainingSet.h);
             trainingSet.detectImage(testImage);
                    frame.addWindowListener(
                            new WindowAdapter() {
                                    public void windowClosing(WindowEvent e) {
                                            System.exit(0);
             frame.setSize(new Dimension(1030,750));
                frame.setVisible(true);
                frame.repaint();
            public void paint(Graphics g) {
                // g.drawImage(averageImage, 0, 0, this);
                       int b = 0;
                       int l = 0;
                      g.drawImage(trainingSet.loadImageFromFile(testImage),b,l,this);
                      g.drawImage(trainingImages[trainingSet.smallestTwoNorm], w, l, this);
                       /* for (int a = 0; a <4; a++) {
                            //g.drawImage(diffImages[a], b, l, this);
                            g.drawImage(trainingImages[a], b, l, this);
                            //g.drawImage(EigenImages[a], b, l, this);
                               b = b + w;
    }Now most of them Image Arrays are assigned their values from the display class and drawBehind method
    class display{
             *  Convert a pixel of array into a buffer image
             *Accepts a vector of integer arrays as its elements
             *Convert each of vector element to an Image object and
             *stores it in an Image array and returns that array .
             * w , h are width and heights of an image.
            public Image[] drawBehind(Vector v,int w,int h) {
                     Image[] temp = new Image[v.size()];
                     for (int a = 0; a < v.size(); a++) 
                       temp[a] = arrayToImage((int[]) v.elementAt(a), w, h);
              return temp;
            }

    And the important part of my own image class is
    class image{
    static File[] imageFiles;                     // of all images we will be loading
    int[] averageImage;                          // averageImage=average value of i'th pixel over all images = sum[i]/NumOfImages
    static int NumOfImages,w,h;                //NumberOfImages,width and height
    static Vector TrainingImageVector;           //All images will be stored in this vector
    static DoubleMatrix2D eigenVectCovMatrix;//EigenVector for the Covariance Matrix of diffImageMatrix
    static DoubleMatrix2D diffImageMatrix;      //Matrix representation of difference images [each column rep. 1 image]
    static DoubleMatrix2D weightMatrix;      // projection of (original images-averageImage) onto eigenfaces
    static Vector diffImageVector;                // Each vector element is an array of difference pixels.
    static Vector EigenVector;
    static Component component;
    static double twoNorm[];                     //TwoNorm of the projected image onto the weight matrix.
    Image[] ImgA;                                    //All actual images are stored in this array.
    int smallestTwoNorm;
    //WriteToFile writer;
    /* Constructor of image class
    String dr specifies the directory where all the images are stored
    Component component is the frame on which all the images will be displayed
    public image(String dr,Component component)
         File f = new File(dr);
         imageFiles = f.listFiles();
         this.component = component;
         NumOfImages = imageFiles.length; // number of images in that directory
         System.out.println("Total number of training images : "+NumOfImages);
         diffImageVector = new Vector();
         TrainingImageVector = loadImgsIntoVector();
         averageImage = findAverageImage(TrainingImageVector);
    // writer = new WriteToFile();
              for (int a = 0; a < NumOfImages; a++)
                   diffImageVector.addElement(findDeviated((int[])TrainingImageVector.elementAt(a)));
         diffImageMatrix = ConvertVectorIntoMatrix(diffImageVector);     
         // eigenVectCovMatrix = ConvertVectorIntoMatrix(EigenVector);
         eigenVectCovMatrix = findEigenVector(diffImageMatrix);
    EigenVector = ConvertMatrixIntoVector(eigenVectCovMatrix); //need in display class
         normalizeColumns(eigenVectCovMatrix);
         System.out.println("Normalized EigenvectorCovMatrix=\n");
         printPartOfDoubleMatrix2D(eigenVectCovMatrix,10,3);
         // END CHANGE
         weightMatrix = project(diffImageMatrix);
    //     classify(ImgA[testImg-1]); //we are not using testImg number
    //     writer.writeEigenMatrix(weightMatrix);
    public image(Component component){this.component=component;}
    // Normalize (2-norm=1) all columns in m
    private void normalizeColumns(DoubleMatrix2D m){
         // for each column
         // normalize the column, that is
         //      find the norm of the column
         //      divide column by the norm
         for(int c=0;c<m.columns();c++){
              double norm=0;
              for(int r=0;r<m.rows();r++)norm=norm+(m.get(r,c)*m.get(r,c));
              norm=Math.sqrt(norm);
              for(int r=0;r<m.rows();r++)m.set(r,c,m.get(r,c)/norm);
    public void detectImage(String fileName){
    classify(loadImageFromFile(fileName));     
    * Place each image into an integer array and stores that array in vector and returns that vector
    * Also stores raw images in array ImgA
    public Vector loadImgsIntoVector() {
         Vector imageVec = new Vector();
         ImgA = new Image[NumOfImages];
              for (int i = 0; i < imageFiles.length; i++) {
              //Get all the images in an array
                   ImgA[i] = loadImageFromFile(imageFiles[i].getAbsolutePath());
                   imageVec.addElement(grabPixels(ImgA[i]));
                   System.out.println(imageVec.size());
                   System.out.println(imageFiles.length);
    return imageVec;
    * Load the image specified by filename
    * @param fileName Description of the Parameter
    * @return Description of the Return Value
    public Image loadImageFromFile(String fileName) {
         Image img = Toolkit.getDefaultToolkit().getImage(fileName);
              try {
                   MediaTracker tracker = new MediaTracker(component);
                   tracker.addImage(img, 0);
                   tracker.waitForID(0);
              } catch (Exception e) {
                   System.out.println("Cant load image file " + fileName);
                   System.exit(0);
         System.out.println(fileName);
         System.out.println("w=" + img.getWidth(null) + "h=" + h);
         return img;
    * Return an array of the pixels from image i
    * pixel x,y gets stored in the width*y+x position of the array
    public static int[] grabPixels(Image i) {
         w = i.getWidth(null);      
         h = i.getHeight(null);
              System.out.println("w=" + w + "h=" + h);
         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.err.println("interrupted waiting for pixels!");
                   System.exit(0);
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                   System.err.println("image fetch aborted or errored");
                   System.exit(0);
         return pixels;
    } When i run it, the output is to my console and displaysTotal number of training images : 7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\amber1.gif
    w=250h=0
    w=250h=300
    1
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\amy1.gif
    w=250h=300
    w=250h=300
    2
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\andrew1.gif
    w=250h=300
    w=250h=300
    3
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\andy1.gif
    w=250h=300
    w=250h=300
    4
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\andyp1.gif
    w=250h=300
    w=250h=300
    5
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\anita1.gif
    w=250h=300
    w=250h=300
    6
    7
    C:\Users\Nick\Desktop\New Folder\TrainingPics\Thumbs.db
    w=-1h=300
    w=-1h=-1
    image fetch aborted or errored
    Press any key to continue...So this is being returned from my image class, grabPixels method.  Can anyone see a logical reason as to why this might be happening?
    cheers                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • PixelGrabber - assistance with code needed

    Hello,
    I have been trying to get the color of a pixel on an image on a program for the past week. I have been advised to use pixelgrabber, and to save results in an array.
    I am trying to understand it by creating a new application just for the purpose of pixelgrabbing, and then coding it properly.
    Following the SUN Documentation, i have this code (no errors):
    package untitled2;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Image;
    import java.awt.image.PixelGrabber;
    import java.awt.image.ImageObserver;
    import java.util.ArrayList;
    public class Frame1 extends JFrame {
        JPanel contentPane;
        BorderLayout borderLayout1 = new BorderLayout();
        public void handlesinglepixel(int x, int y, int pixel) {
                int alpha = (pixel >> 24) & 0xff;
                int red   = (pixel >> 16) & 0xff;
                int green = (pixel >>  8) & 0xff;
                int blue  = (pixel      ) & 0xff;
              // Deal with the pixel as necessary...
           public Frame1() {
            try {
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                jbInit();
            } catch (Exception exception) {
                exception.printStackTrace();
        private void jbInit() throws Exception {
            contentPane = (JPanel) getContentPane();
            contentPane.setLayout(borderLayout1);
            setSize(new Dimension(400, 300));
            setTitle("Frame Title");
    }Help needed:-
    1-Can some show me where to put the code to produce the appropriate image? (do i use normal/buffered/etc)
    2-Do i make an array and transfer the values of red,green,blue to postion [0][1][2]?
    3-I believe i need to convert the values to an int. How is this done?
    4-The "proper" program where this will be used will create multiple images based on user input. The images will be created via a loop.
    Are there any issues i should be aware of ? As i understand, each pixelgrabber is unique to each image.. If i have 1000 images will that mean 1000 pixelgrabbers? (slow performance).
    Where appropriate, if you could direct me to the relavent tutorial i am happy to read and learn, although i would need help as to the exact location to put the code. For question (1), as i am unsure of the exact image, i would prefer a piece of code (the image is accessed via "temp2.png").
    Regards
    David55

    UPDATE
    This code shows the rgb value of the image at a specific point (entered in code). all that is needed is to find coordinates within image.
    Can anyone help clean code or offer advice?
    package untitled2;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.Image;
    import java.awt.image.PixelGrabber;
    import java.awt.image.ImageObserver;
    import java.util.ArrayList;
    import java.awt.*;
    import com.borland.jbcl.layout.XYLayout;
    import com.borland.jbcl.layout.*;
    import javax.swing.JLabel;
    import javax.swing.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    public class Frame1 extends JFrame {
        JPanel contentPane;
        BorderLayout borderLayout1 = new BorderLayout();
        XYLayout xYLayout1 = new XYLayout();
        private BufferedImage bi[];
        JPanel jPanel1 = new JPanel();
        XYLayout xYLayout2 = new XYLayout();
        public void handlesinglepixel(int x, int y, int pixel) {
                int alpha = (pixel >> 24) & 0xff;
                int red   = (pixel >> 16) & 0xff;
                int green = (pixel >>  8) & 0xff;
                int blue  = (pixel      ) & 0xff;
                // Deal with the pixel as necessary...
        public Frame1() {
            try {
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                jbInit();
            } catch (Exception exception) {
                exception.printStackTrace();
         * Component initialization.
         * @throws java.lang.Exception
        private void jbInit() throws Exception {
            contentPane = (JPanel) getContentPane();
            contentPane.setLayout(borderLayout1);
            setSize(new Dimension(400, 300));
            setTitle("Frame Title");
            jPanel1.setBackground(Color.white);
            jPanel1.addMouseListener(new Frame1_jPanel1_mouseAdapter(this));
            jPanel1.setLayout(xYLayout2);
            contentPane.add(jPanel1, java.awt.BorderLayout.CENTER);
            bi = new BufferedImage[1];
            File f = new File("temp2.png");
                //  Read in a BufferedImage from a file.
                       BufferedImage bufferedImage = ImageIO.read(f);
                       ImageIO.write(bufferedImage, "png", f);
    bi[0] = bufferedImage;
                       //  Convert the image to an RGB style normalized image.
               //        bi[0] = new BufferedImage(bufferedImage.getWidth(),
               //            bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
               //       bi[0].getGraphics().drawImage(bufferedImage, 198, 100, this);
        public void paint(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(bi[0], 110, 110,null);
        public void jPanel1_mouseClicked(MouseEvent e) {
            int mouseX = e.getX();
            int mouseY = e.getY();
            int rgb = bi[0].getRGB(1, 98);
            int red = ((rgb >> 16) & 0xff);
                int green = ((rgb >> 8) & 0xff);
        int blue = ((rgb ) & 0xff);
        rgb = (red << 16) | (green << 8) | blue;
            System.out.println((red ) + " " +  (green ) + " " + blue);
    System.out.print(mouseX + " / " + mouseY + " ");
    class Frame1_jPanel1_mouseAdapter extends MouseAdapter {
        private Frame1 adaptee;
        Frame1_jPanel1_mouseAdapter(Frame1 adaptee) {
            this.adaptee = adaptee;
        public void mouseClicked(MouseEvent e) {
            adaptee.jPanel1_mouseClicked(e);
    }

  • Problem with ImageProducer/PixelGrabber

    I'm having a problem using PixelGrabber in my applet, that seems to be related to caching. I load an image through plain old Applet.getImage(), track that it's loaded via MediaTracker, then use PixelGrabber to grab the image into an integer array, all using your basic textbook code. What I find in testing is that even after the image is loaded (apparently either from a cache or from a URL) the PixelGrabber operation loads the image across the network all over again(!) every time, which I can see by watching debugging output and watching network activity, apparently ignoring the image data already obtained, which essentially doubles the image load time (a problem on modems) when using PixelGrabber. I'm wondering if this is a bug in the ImageProducer object, or if there's something about the implementation of PixelGrabber that specifically prevents using existing image data. I'm testing with IE, JVM version 5.0.0.3805, which is the target platform. Any help would be greatly appreciated!
    -Bob

    That's because your ImageProducer is still the original image. Just because you've snagged the pixels doesn't mean you've changed the source of the image. Once you have the data in an array create a new MemoryImageSource. Make a new image using that as a source. Note that the createImage method shown in the API is from java.awt.Component.

  • Pixelgrabber problem

    Hi,
    I have a problem with an applet which loads an image from url. First I load the image (png) and second I try to grab it (with pixelgrabber) in order to extract a pixel array (integer array) . But there is a problem and the pixel array is empty (note : If I use a java pluggin I works fine but IE VM doesn't work fine with png image)
    I wonder if it were possible to transform a byte array (that I use to create my image) directly to a pixel array without create the image
    Any idea ?

    If I remember correctly you need to go back to java 1 version 1.1.8 (or how ever they did the numbeing back then) pre-java 2 for compliance with MS's product. MS did their normal thing and changed the language to suite thier model better, which in and of itself sounds like a decent enough idea, but the effect is--if you develop with MS's product, then everyone else is broken. If you develop with Sun's product and use any of the newer features--then MS is broken.
    You just have a bit of code which is not supported in the MS VM, try to find the old standard from Java 1 and stick with it.

  • PixelGrabber is intermittently slow

    Hi All,
    PixelGrabber has some perfomance problems and there is a bug related to it here (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4835595). However I am facing a bug where a offscreen image sometimes gets slow while I am running the PixelGrabber, this is the stack trace :
    at java.awt.image.DirectColorModel.getsRGBComponentFromsRGB(DirectColorModel.java:305)
    at java.awt.image.DirectColorModel.getRed(DirectColorModel.java:353)
    at java.awt.image.DirectColorModel.getRGB(DirectColorModel.java:438)
    at java.awt.image.PixelGrabber.setPixels(PixelGrabber.java:595)
    at sun.awt.image.OffScreenImageSource.sendPixels(OffScreenImageSource.java:130)
    at sun.awt.image.OffScreenImageSource.produce(OffScreenImageSource.java:161)
    at sun.awt.image.OffScreenImageSource.addConsumer(OffScreenImageSource.java:37)
    - locked <0x185b41c8> (a sun.awt.image.OffScreenImageSource)
    at sun.awt.image.OffScreenImageSource.startProduction(OffScreenImageSource.java:51)
    at java.awt.image.PixelGrabber.grabPixels(PixelGrabber.java:242)
    - locked <0x185b4190> (a java.awt.image.PixelGrabber)
    at java.awt.image.PixelGrabber.grabPixels(PixelGrabber.java:209)
    Would somebody know if the intermittent slowness can be associated to the bug above ? ( in the bug it states it always happens) Has somebody ever had the same problem ?
    Thanking you in advance
    Ary Alves

    Hi, there are ways to do it if you can live with certain restrictions.
                BufferedImage img=new BufferedImage(32,32,BufferedImage.TYPE_INT_ARGB);
                img.setRGB(10,15,0x01020304);   // a=1 r=2 g=3 b=4
                WritableRaster r=img.getRaster();
                DataBuffer db=r.getDataBuffer();
                if (db.getDataType() != DataBuffer.TYPE_INT)
                    throw new IllegalStateException("Hey that must be a int!");
                if (db.getNumBanks() != 1)
                    throw new IllegalStateException("Uh - Someone else got to do this job!");
                DataBufferInt dbi=(DataBufferInt)db;
                int[] data=dbi.getData();           
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));
                // Test: No coy
                data[10+32*15]=0xaabbccdd;
                System.out.println(" Pixel (10,15) = "+Integer.toHexString(data[10+32*15]));As you see it works best if you can set the pixel format and if it only contains a single array of data (i.e. bank).

  • PixelGrabber + Import

    1. What exactly does the PixelGrabber do? How can I use it(or another technology if better) to differentiate colors on a background for collision pupposes in a game?
    2.How do I call methods and variables from one class in another. I know it should be simple, but I can't seem to find it anywhere, and don't know what words to use in a search term.

    only for black and white, you could still construct the scenery with 2D and a general path which is pretty flexible and check for intersection. it hasn't to do with 3D.
    but if you want to detect the pixel values, you can use the Raster() and DataBuffer classes in java.awt.image. with bufferedImages. check out the java2D forum for examples. I posted a reply exactly doing that a short while ago.
    but depending on the size of your scrolling background you should really only check the areas you need (your current ship position for example), otherwise its going to be pretty slow.

  • Call to PixelGrabber(???,

    I want to call the PixelGrabber(...) method, but I need help figuring out the correct value to send in for the first parameter.
    Basically I am loading an image "theSky.gif" into a Graphics2D object using the method drawImage(...)
    The Graphics2D object named "_2DSkyImage" will at various times during the program manipulate and change the copied image of "theSky.gif".
    Then I want to be able to send the modified image into the first parameter of the method PixelGrabber(...). The problem is that I do not know how to get a handle on the image referenced by the object _2DSkyImage, and then pass it into the first variable of PixelGrabber(...). Which I think would be of type ImageProducer (Not sure!)
    Anyway, here is the code. I hope the question is clear. I will award 4 points for this question and would appreciate help from someone who feels they can truly help me out. Thanks in advance,
    Amy Danough,
    the code is below:
    Image imgSKY_IMAGE;
    imgSKY_IMAGE=getImage(getDocumentBase(),"theSky.gif");
    private Graphics2D _2DSkyImage;
    private BufferedImage biSkyBuffer;
    biSkyBuffer = new
    BufferedImage(imgSkyImage.getWidth(this),
    imgSkyImage.getHeight(this),
    BufferedImage.TYPE_INT_ARGB);
    _2DSkyImage = biSkyBuffer.createGraphics();
    _2DSkyImage.drawImage(imgSKY_IMAGE,0,0,this);
    // ?????? represents the image referenced by _2DSkyImage but I don't
    // know how to get to the image which is referenced by _2DSkyImage.
    PixelGrabber pg;
    pg = new PixelGrabber(??????,0,0,width,height,image_array,0,width);

    At the moment, I don't really feel like writing the code verbatim to illustrate for you what I am attempting to explain. I think the confusion stems from a lack of understanding as to how the object references in your code interoperate. I will attempt to explain, and maybe code later if I feel up to it or if someone doesn't beat me to the punch. :) (It's Saturday, and I don't really want to spend it indoors coding....)
    Your Graphics2D object _2DSkyImage is a reference to the Graphics2D object that is generated by the BufferedImage biSkyBuffer. Thus, when call any of the drawXXX() methods of your Graphics2D reference, it is drawing that information on to your image. If when you called the PixelGrabber constructor and gave it a reference to your BufferedImage, then, using the Graphics2D object drew something on your BufferedImage, it would (possibly) show up in the PixelGrabber. This is what we call a side-effect (though intended in this case). Once the image has been changed after you drew on it, you may have to tell the PixelGrabber object to reload the image data once it has been altered (via the Graphics2D object) so that it will track the changes.
    The worst case scenario is that you'd have to reinstantiate the PixelGrabber object every time you altered the image, and if that was the case, I would consider ditching the implementation. However, you shouldn't have to do this because PixelGrabber does have methods that allow you to reload pixel data without reinstantiating.
    Hopefully that clears it up. If not, let us know and we'll give it another shot. ;)
    -Dok

  • PixelGrabber.grabPixels() doesnt work

    I try to save my canvas object. It works always fine, but it seems that my personalJava (ARM) has a problem when my PixelGrabber calls grabPixels(). I tried it with milli-seconds, doesnt work.
    Then I deleted the grabPixels()-Method in my source and I get a black image.
    does anyone have the same problem or can help me to find perhaps an other solution?
    I tried it with pngEncoder from http://www.keypoint.com.

    Could you post your code so we can see what is going on?

  • Problem using PixelGrabber ( cannot resolve symbol ) - newbie

    Hi All,
    I have a problem with my short program because the compiler write this (jdk1.4) :
    img.java:17: cannot resolve symbol
    symbol : constructor PixelGrabber (java.awt.Image,int,int,int,int,int[],int)
    location: class java.awt.image.PixelGrabber
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this
    ),image.getHeight(this),pixels,0);
    ^
    1 error
    ... And I wrote that in my code :
    ( all is OK, the bug is only when I uncomment the line where the PixelGrabber object
    is needed in my program ).
    Thanks if you have any idea of solution to solve this problem or a doc,
    ( I don't find the answer to my problem in http://java.sun.com/j2se/1.4/docs/api/java/awt/image/PixelGrabber.html ),
    import java.awt.*;
    import java.awt.image.*;
    import java.applet.*;
    import java.awt.image.PixelGrabber;
    public class img extends Applet {
    Image image;
    int pixels[];
    public void init() {
    image = getImage(getDocumentBase(), "rouge.jpg");
    pixels = new int[image.getWidth(this) * image.getHeight(this)];
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
         pg.grabPixels();
    public void paint(Graphics g) {
              String s = Integer.toString(pixels[5], 16);
              g.drawString(s, 50, 50);

    Hi,
    PixelGrabber needs one more parameter scansize (width).
    change this line;
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0);
    to:
    PixelGrabber pg = new PixelGrabber(image,0,0,image.getWidth(this),image.getHeight(this),pixels,0, image.getWidth(this)
    );

  • PixelGrabber.getPixels returns an int[] full of -1's

    I'm trying to get the pixels of a certain area of a screen shot but all I can get is an array full of -1's. I'm trying to get the RGB values so I can compare them against another image. Can anyone look at my code and suggest a fix or new method? Thanks. private void takeScreenShot() throws AWTException, IOException {
            Robot robot = new Robot();
            BufferedImage image = robot.createScreenCapture(bounds);
            PixelGrabber grabber = new PixelGrabber(image,550,320,20,18,false);
            try {
                grabber.grabPixels();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            int[] data = grabber.getPixels();
    }

    Ok, I tried BufferedImage.getRGB() but it still returns all -1's in the array. Here is the updated code:private void takeScreenShot() throws AWTException, IOException {
            Robot robot = new Robot();
            BufferedImage image = robot.createScreenCapture(bounds);
            int[] data = new int[20*18];
            image.getRGB(520,320,20,18,data,0,20);
    }

  • How can i user  PixelGrabber in javafx.scee.image.Image

    how can i user PixelGrabber in javafx.scee.image.Image

    You can either get a java.awt.BufferedImage snapshot of the Image, and use a PixelGrabber with that:
    import javafx.scene.image.Image ;
    import javafx.embed.swing.SwingFXUtils ;
    import java.awt.image.BufferedImage ;
    import java.awt.image.PixelGrabber ;
    Image img = ... ;
    BufferedImage bImage = SwingFXUtils.fromFXImage(img, null);
    PixelGrabber grabber = new PixelGrabber(bImage, ...);Or, you can use a javafx.scene.image.PixelReader, which has essentially the same functionality:
    import javafx.scene.image.Image ;
    import javafx.scene.image.PixelReader ;
    import javafx.scene.image.PixelFormat ;
    Image img = ... ;
    PixelReader reader = img.getPixelReader();
    int[] pixelArray = ... ;
    int x, y, w, h ; // bounds of image portion from which to read pixels
    reader.getPixels(x, y, w, h, PixelFormat.getIntArgbInstance(), pixelArray, 0, w); // see javadocs for full description of parameters(The second solution is probably better; the first might be useful if you have a lot of existing functionality that relies on a PixelGrabber.)

Maybe you are looking for