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

Similar Messages

  • Converting image into byte array

    Hi all,
    How to convert an integer array image into byte array ?
    here i have a image like this :
    private static int pixelArray[] = {
    0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
    0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
    From this one i create image like this one :
    Image image = Image.createRGBImage(pixelArray, width, height, true);
    Now i want to convert that pixelArray into byte array ? how to do this
    additionally i want to send this byte array to servlet .
    thanks in advance.

    Hi,
    If you want to convert your int array to a byte array you should
    split each integer into 4 bytes to avoid losing information. You can
    rebuild your integer array later if you need to. I think this code
    will work (i havent tested it):
    byte[] pixel= new byte[pixelArray.length<< 2];
    for (int i= pixelArray.length- 1; i>= 0; i--) {
      int aux= i<< 2;  // i* 4 = i<< 2
      pixel[aux]=    (byte) (pixelArray>> 32);
    pixel[aux+ 1]= (byte) (pixelArray[i]>>> 16);
    pixel[aux+ 2]= (byte) (pixelArray[i]>>> 8);
    pixel[aux+ 3]= (byte) pixelArray[i];
    Greets.

  • How can I copy pictures from google images into MS word for iMac

    how can I copy pictures from google images into MS word for iMac.
    How can I copy pictures from iphoto to MS word for iMac.

    As MS Word is not an Apple product, you may do better posting in the MS forums:
    Office for Mac forums
    Most people find them very helpful

  • Converting an image into numeric array?

    I want to sum all the pixel values in a image. I was thinking of using the Add Array Elements VI. Is their an easy way to convert an U8 or an I16 bit image into a numeric array? Thank you in advance.

    Is this a BW image? (If the image is paletted or color, a summing operation is poorly defined! )
    Just convert your image data to a 2D boolean array using unflatten pixmap, then feed the 1bit pixmap to "boolean to 0..1" followed by the SUM operation (in case it overflows, you might want to convert it to a better representation before summing, e.g. DBL. "boolean to 0,1" generates I16).
    Message Edited by altenbach on 06-01-2005 02:44 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    SumImage.png ‏2 KB

  • Combining information from multiple images into a single output

    So I'm working on a class that takes input from three buffered images. The buffered images I will be using were covered in some detail [Here in this thread|http://forums.sun.com/thread.jspa?threadID=5401006&tstart=0] for the sake of reference.
    I'll be providing 3 buffered images where the value of every pixel is the ID of the cluster. What I'm planning on doing now is looking at each cluster in each of the 3 buffered images I give the class to process.
    public BufferedImage amalgamate(BufferedImage hueTemp, BufferedImage contrastTemp, BufferedImage textureTemp){
            imgWidth = hueTemp.getWidth();
            imgHeight = hueTemp.getHeight();
            hueRaster = hueTemp.getRaster();
            contrastRaster = contrastTemp.getRaster();
            textureRaster = textureTemp.getRaster();
            amalgamImage = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            amalgamWriter = amalgamImage.getRaster();
            imagePixelCount =  imgHeight * imgWidth;
            for (int x = 0; x < imgWidth; x++)
            for (int y = 0; y < imgHeight; y++) {           
                // assigns pixel values from each buffered image
                hueValue = hueRaster.getSample(x, y, 0);
                contrastValue = contrastRaster.getSample(x,y,0);
                textureValue = textureRaster.getSample(x, y, 0);
                // reset values of integers storing pixel counts
                huePixelCount = 1;
                contPixelCount = 1;
                textPixelCount = 1;
                //. loop iterates through images and produces a pixel count for each of the
                //currently assign pixel values (each pixel value is also used as
                // the ID for each cluster)*/
                for (int i = 0; i < imgWidth; i++)
                for (int j = 0; j < imgHeight; j++) {
                    if (hueRaster.getSample(i, j, 0) == hueValue) huePixelCount ++;
                    if (contrastRaster.getSample(i, j, 0) == contrastValue) contPixelCount ++;
                    if (textureRaster.getSample(i, j, 0) == textureValue) textPixelCount ++;
                }//end of i,j loop
                // this section will determine is the cluster is valid (i.e. makes up
                // more than 5% of the total percentage of pixels in the image)
                if (huePixelCount >= (imagePixelCount * 0.05)) hueValidCluster = true;
                if (contPixelCount >= (imagePixelCount * 0.05)) contValidCluster = true;
                if (textPixelCount >= (imagePixelCount * 0.05))  textValidCluster = true;
                //loop iterates and the Writable Raster will set the pixel values
               // of the output image to red, green or blue for Hue, contrast and
               //texture respectively and set all other pixels to black.
              //I'm using RGB so that I can use a different channel value for
              //each of the three, so that overlap will result in a new colour
              //(overlap between all 3 should = white pixel)*/
                for (int a = 0; a < imgWidth; a++)
                for (int b = 0; b < imgHeight; b++) {
                    //This is my original method I devised
                    if (hueValidCluster == true && hueRaster.getSample(a, b, 0) == hueValue) amalgamWriter.setSample(a, b, 0, 256);
                    else amalgamWriter.setSample(a,b,0,0);
                    if (contValidCluster == true&& contrastRaster.getSample(a, b, 0) == contrastValue) amalgamWriter.setSample(a,b,1,256);
                    else amalgamWriter.setSample(a,b,1,0);  
                    if (textValidCluster == true&& textureRaster.getSample(a, b, 0) == textureValue) amalgamWriter.setSample(a,b,2,256);
                    else amalgamWriter.setSample(a,b,2,0);
                  //When the image returned a completely black output I tried a different
                  //approach along these lines assuming the .setPixel method
                 //would have done what I wanted.
                  if (hueValidCluster == true && hueRaster.getSample(a, b, 0) == hueValue) amalgamWriter.setPixel(a, b, redArray);
                    else amalgamWriter.setPixel(a,b,blackArray);
                }//end of a,b loop
                //Reset booleans for next pixel in the original x,y loop.
                //I've been using ping to make sure the thing doesn't crash while it's running.
                hueValidCluster = false;
                contValidCluster = false;
                textValidCluster = false;
                ping++;
                System.err.println(""+ ping);
            }//end of x,y loop
            return amalgamImage;
        }//end of amalgamate method
    }//end of AmalgamationAs previously hinted the class seems to run to completion, but the image returned is always black so the pixels aren't being set or they're somehow being reset?
    If the error is due to me setting the pixels in the output image incorrectly then the root of the problem is temporarily eluding me.
    I'm not sure if there are compatability problems between USHORT (which is the format the input images are in) and an INT_RGB BufferedImage which could be the cause so I thought I'd mention that.
    It's also crossed my mind that in using a loop inside a loop inside a loop I possibly have done something wrong there.
    Thought I'd throw this problem out there. I've been de-bugging this one for a while.

    amalgamWriter.setSample(a, b, 0, 256);
    amalgamWriter.setSample(a,b,1,256);
    amalgamWriter.setSample(a,b,2,256);For the image type you are using, you only have 8 bits of precision each color channel. That means only a number in the range [0,255] is valid for the sample. The value 256 is equivalent to setting the sample to 0. That is ((byte) 256) = 0.

  • Putting data read from a StreamTokenizer into an array.

    I need to put the data that I have read from a file using a streamtokenizer into an array, so that I can use it later on in my program.
    If anyone can help I would be grateful!!

    Here's a link that should help. It even includes an example:
    http://java.sun.com/docs/books/jls/first_edition/html/javaio.doc14.html

  • How to get input from keyboard scanner into an array

    This is probably a very basic question but I'm very new to java..
    My task is to reverse a string of five digits which have been entered using keyboard scanner.
    E.g. - Entered number - 45896
    Output - 69854
    I used the StringBuffer(inputString).reverse() command for this, but i need a more basic method to do this.
    I thought of defining an array of 5
    int[] array = new int [5];
    and then using,
    Scanner scan = new Scanner(System.in);
    to enter the numbers. But I can't figure out how to get the five input numbers into the array.
    If I can do this I can print the array in reverse order to get my result.
    Any other simple method is also welcome.

    Hey thanks for the quick reply,
    But how can I assign the whole five digit number into the array at once without asking to enter numbers separately?
    E.g. - if entered number is 65789
    Assign digits into positions,
    anArray [0] = 6;
    anArray [1] = 5;
    anArray [2] = 7;
    anArray [3] = 8;
    anArray [4] = 9;
    I'm really sorry but I am very new to the whole subject.

  • Conversion of image into byte array

    I have a problem in converting .png image into bytestream, if anyone can help in this pls do so.....

    Hi,
    To convert an Image to bytes you can use the Image.getRGB() method.
    http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#getRGB(int[], int, int, int, int, int, int)
    -Henrik

  • Procedure to grab PDF from fileSystem store into LONGRAW Datatype.

    Hi All,
    I have found there are ways to store PDF's from file system into BLOB datatype, but not into LONGRAW. In PeopleSoft we have only LONGRAW type.
    Can any one send some hints to load PDF's from filesystem into Oralce 10g LONGRAW column.
    Thanks in Advance.

    Hi All,
    I have found there are ways to store PDF's from file system into BLOB datatype, but not into LONGRAW. In PeopleSoft we have only LONGRAW type.
    Can any one send some hints to load PDF's from filesystem into Oralce 10g LONGRAW column.
    Thanks in Advance.

  • Moving data string from a jtextarea into an array

    i was looking for some advice. how would i be able to take chunks of text on a paragraph by paragraph basis and enter them into an array. which would result in paragraph1 in array 0, and so on. is this possible to do? i have never really used straing arrays before, and if anyone knows of any online tutorials it would be a great help
    thank u

    here you go, forgive the gui, very sloppy looking, press the Click me button to store the jtextarea data into the array and show output button to see what the value stored in the array is. there are 2 classes:
    class MyMain {
          public static void main(String args[]){
              MyMain main = new MyMain();
              main.createIt();
          public void createIt() {
              MyFrame frame = new MyFrame();
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class MyFrame extends JFrame {
          String[] myString = new String[1];
          JTextArea textArea = new JTextArea();
          JButton myButton = new JButton("Click me");
          JButton outButton = new JButton("Show output");
          MyFrame() {
              myButton.addActionListener(new ButtonListener());
              outButton.addActionListener(new OutListener());
              getContentPane().setLayout(new GridLayout(1,3));
              getContentPane().add(myButton);
              getContentPane().add(textArea);
              getContentPane().add(outButton);
              setVisible(true);
          class ButtonListener implements ActionListener{
              public void actionPerformed(ActionEvent e){
                  myString[0] = textArea.getText();
          class OutListener implements ActionListener{
              public void actionPerformed(ActionEvent e) {
                  System.out.println(myString[0]);
    }

  • How can I convert a bitmap image into an array in LabVIEW 6.0.2, then to a spreadsheet for further analysis without NI-IMAQ or Vision?

    I do not have NI-IMAQ or NI Vision.
    I acquired the image using a picolo board then just saved it as a bitmap file.

    You want to convert it to an array of what? Of numbers? Of LabVIEW colors?
    The "Read BMP File.vi" VI outputs a 1-D array of the pixels, but I suspect it is not exactly in the format that you need. I am NOT sure, but I think that each group of 3 elements of that 1-D array (which is inside the cluster "image data" that the VI outputs) represents the red, green and blue levels of a single pixel (but it may be hue, saturation and lum.). Also, since it is a 1-D array, you would have to divide it by the width (which is also included in the "image data" cluster) to get some sort of 2-D array of data.
    You can find the "Read BMP File.vi" VI in the functions palete> "Graphics & sound">"Graphics Formats".

  • 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 :)

  • Unable to read images into an array

    Hi there,
    I hope that someone will be able to help me. I have set up a program that will set the loop count to the number of images in the folder (orange input). With each execution of the loop, I would like an image to be read from file (using IMAQ ReadFile) and then stored to an array (purple output). Please find the screenshot attached with a snip of the code in question and the error that results from executing the vi (highlights the IMAQ ReadFile vi).
    I do have 5 images with the name: image0.png - image4.png in the folder directory specified by "Image Read File Path" and made sure that the path appends the actual name to the file path.
    I am fairly new to Labview programming (I have searched for a solution and troubleshooted as much as I can) and I hope I have provided enough information.
    Kind regards,
    Richard
    Attachments:
    Program.PNG ‏19 KB

    I wonder if the extra backslash is messing up the path. "Build Path" handles the file seperator. Right click on the final path and select Probe, or create and indicator to see the path.
    Attachments:
    Untitled.png ‏3 KB

  • Can i restore from sparse image to raid0 array

    im tring to boot from the SL disk and restore my disk image to my raid0
    or will it break my raid0?

    Your RAID should have been built with SL to begin with in order to work.
    Why not boot from a bootable backup instead? a must for anyone but esp. running RAID.
    You will need to erase, so you should recreate the array anyway.

  • Image comparison to extract odd pixels from one image

    Hello,
    I am just trying to make one screen capture application which will send captured image to a remote system. I have succeeded in making the basic screen capture application using robot class. The image has to be refreshed at a rate of 1 or 2 frames per second for my application. If I transmit the complete image at this rate, then bandwidth problem will occur. Is there any way where I can compare 2 images, one base image and other newly captured image and takes out only the pixels which has changed and transmit only that pixel to the remote system where I can rebuild the image with transmitted pixels.

    shivgaikwad, please read the moderator response to your first post on this forum in this thread:
    [http://forums.sun.com/thread.jspa?threadID=355342]
    I'm locking your account for 24 hours. When you are able to post abgain,. please post your question in a new thread. Continuing to post to old dead threads may lead to your account being locked for a longer period, or even indefinitely.
    Also locking this zombie thread.
    db

Maybe you are looking for

  • Error message in BEx Report Designer

    Hello, I get an error message when I try to add a data provider in Report Designer It says: "Error when loading query metadata Check the query and portal settings" I can see no reason why my query should not appear in my report. Has anyone seen a sim

  • ITunes 7 playing only from left and right channels with 5.1 speakers

    I have an SB Audigy 1 sound card with Creative Inspire 5200 digital 5.1 speakers, and iTunes only plays audio from the left and right speakers, and the subwoofer. The other 3 speakers work; I've tested them.

  • Passing a variable into workflow

    I know u can pass variables from a form into a workflow using processInputs.....but let's say I have a update workflow and there's some attribute that has changed on the user that requires the update workflow to trigger the disable workflow.....let's

  • What authorizations to give to developers in the production environment

    Hi, We have setup our development PI 7.1 environment and are now ready to setup production.  Can someone point me in the right direction for determining which authorizations need to be given to the PI developers in the production environment? Do they

  • Compare two fields and populate a third

    I am trying to do the following: Filed A number of days leave left Field B Total number of days requested (some of other Fields) Field C = A - B Field D = Listed number of days unpaid to be taken If C < 0 then D = C I am using the following code