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

Similar Messages

  • Get pixel coordinates in image with mouseclick

    Hey there
    Im a beginner at labview, so i walked into a little problem.
    I want to know if there is a way to get pixel coordinates from an imagefile with a mouseclick in labview, this is to use the coordinates in order to calibrate the image without using the vision assistent.
    THx with regards
    jens dassen

    I'm not sure if this is something new with newer versions of LabVIEW, but I just solved this problem using a property node for the image indicator. See images below. Super easy!
    Cheers!
    James
    LabVIEW Professional 2014
    Attachments:
    Capture.PNG ‏8 KB
    Capture1.PNG ‏5 KB

  • 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

  • Profile Imanges are not getting deleted from Profile Image library

    Hi,
    If I go mysite and edit my profile and set a profile images and save the changes. Image is uploaded to profile Image library in the root of the mysite.
    I Edit my profile again and this time I remove the profile image and save the changes. Image is not getting deleted from the profile Image library.
    as per my understanding it should get deleted. My site clean job is running. user profile is active in AD.
    Thanks
    Omkar

    My first question would be is it a big deal if the picture doesnt get deleted from the libarary?  My understanding is that the profile picture field is a URL link, the first time you add a picture it will provision 3 copies of differing sizes to the
    library.  When you "remove" the picture, it just empties out the picture URL field.  Which is a nice hidden recovery if someone accidently deletes a profile photo they really wanted (Or if your company really locks down picutures so you only get
    a choice of a couple avatars instead of a personal photo).
    Similar issue:
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/17bc8538-568f-4fff-8933-458fdba4b701/delete-user-profile-picture-in-sharepoint-2010-when-account-is-deactivated-or-deleted-from-ad?forum=sharepointadminprevious
    and response:
    Since the user photo library follows certain standards OOB:
    http://iedaddy.com/2010/12/sharepoint-2010photo-management-for-social-mysites/
    I would say just create a small script that will periodically read the UPS and make sure there are no photos sitting in the library not associated to an account... here's an example of accessing the User Profiles w/ Powershell:http://iedaddy.com/2010/06/sharepoint-2010-updating-user-profile-properties-with-powershell/
    You would just modify it to delete image files whose name is not associated to an existing NTName in the UPS.
    ieDaddy
    Blog: http://iedaddy.com
    Twit: @iedaddy

  • Need help!-----How to get pixel from pixel location??

    Hi, I have the location of a pixel (x, y), how to get the pixel value which will be used in DirectColorModel cm.getRGB(int pixel)?
    thanks a lot!!!

    Hi, my image is created by Toolkit.createImage(byte[]). I think I should use PixelGrabber to grab all pixels value to int[], use location(x,y) to get pixel index(y*width+x), then use ColorModel.getRGB(int pixelIndex) to get the rgb value at that location, right? is there any other way to do it?
    thank you.

  • Can i get information from an image file??

    sorry about my poor english
    Hi
    I need to get info from an jpeg or any format of image file. for example a form with slectable tems.
    The other way i have is to control a scanner and when im scanning the form get the info. i dont know if there is any api for this.
    Thanx

    look in ImageIcon api
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/ImageIcon.html
    in the Method Summary
    + the upper class
    http://java.sun.com/j2se/1.5.0/docs/api/javax/accessibility/Accessible.html

  • How to get Byte[] from an image object?

    This are the codes that i have tried, it did an resized.jpg but the file doesnt consist of the image. My program will stream the .jpg file using fileconnection then i resize the image and created the new image using image.createRGBImage(). Lastly, i need to save the resized image as a jpeg file but i failed to do so..
    byte[] jpegData = ImageByteConverter.getByteArray(image);
    OutputStream out = fconn.openOutputStream();
    out.write(jpegData,0,jpegData.length);
    * This method converts a int-array, containing all RGB values for the image, to
    * a byte-array containing all RGB values.
    public static byte[] getByteArray(Image image){
    // Allocate new memory for the int-array and fill the array in the getRGB method.
    int[]raw = new int[image.getWidth() * image.getHeight()];
    image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
    byte[]rawByte = new byte[image.getWidth() * image.getHeight() * 4];// ARGB
    int a, r, g, b;
    int n = 0;
    // loop through the int-array and get the 4 bytes of each value to the byte-array.
    // since java isn't supporting unsigned bytes we need to store the ARGB values from -128 to 127
    // where -128 = 128, -127 = 129 and -1 = 255
    for(int i=0; i<raw.length; i++){
    // Right-shift the values to fit in a byte.
    int ARGB = raw;
    a = (ARGB & 0xFF000000) >> 24;
    r = (ARGB & 0xFF0000) >> 16;
    g = (ARGB & 0xFF00) >> 8;
    b = (ARGB & 0xFF);
    rawByte[n] = (byte)b;
    rawByte[n+1] = (byte)g;
    rawByte[n+2] = (byte)r;
    rawByte[n+3] = (byte)a;
    n+=4;
    raw=null;
    return rawByte;
    Thanks in advance.

    you can do follwoing but not sure whether thats what you want.
    Also not sure whether its the best way.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "PNG",baos);
    InputStream in = new ByteArrayInputStream(baos.toByteArray());

  • Getting pixels from jtextarea

    Hi, I have a jtextarea which I want to analyze by extracting from it all of the pixels (pixel by pixel in row order). I want to have arrays of pixels representing the black pixels in the jtextarea (each array represents a row).
    I'll be happy to recieve any counsel.
    Thanks

    this should help
    http://java.sun.com/j2se/1.3/docs/guide/2d/spec/j2d-image.fm3.html

  • 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

  • Best Way to get part of a image

    Hi , i´m trying to achieve a behaviour with bitmaps but a little bit confused.
    Objective:
    (As shown in image attached)
    I have a Movieclip with a static Shape on Stage ( Let´s say ... a star)
    I would like to load a image(img1) , then i would be able to, rotate, zoom , and pan the image(img1).
    Then i would have only the star but filled with the part of the image that fitted that star.
    I was trying to  get bitmapData from the image, then draw the star on the image.... And at end, compare color pixels and only getting the ones i want to.... but i get a big mess with the rotations, scale and position of star to be exactly on the place it should be draw...
    Something tell´s me that i´m missing a point and it should be easier...
    Can anyone give me directions ?
    It´s a kind of masking, but i want to save that image only then...
    Thanks in advance!

    I would:
    1) Move and translate your image clip
    2) Set the star as the mask
    3) Once the mask is applied, use BitmapData.draw to draw the masked image to a new bitmap data
    4) TADA!
    As far as I am aware, 'draw' should respect masks? If it doesn't then you may need to put clip+mask inside another DisplayObject and draw that.  Some psuedo code (not tested, and simplified):
    // Parent object
    var canvas : Sprite = new Sprite();
    canvas.addChild( clip );
    canvas.addChild( star );
    // Manipulate your image
    clip.rotation = 35;
    clip.scaleX = clip.scaleY = 1.2;
    // Set mask and position it
    clip.mask = star;
    star.x = 40;
    star.y = 20;
    // Create a bitmap data and draw to it
    bitmapData = new BitmapData( Math.ceil(canvas.width), Math.ceil(canvas.height), true, 0x00000000 );
    bitmapData.draw( canvas, ...... );
    // You may need to use canvas.getBounds and create a matrix to get 'canvas' positioned correctly on the bitmapData
    Hope it helps,
    Peter

  • Creating Thumbnail from an Image with transparent background

    Hello,
    I want to create a thumbnail image of size 200 x 200 pixels from an image of any size.
    As the thumbnail is square, I'm centering the image according to size.
    The code I'm using is working fine BUT after centering and resizing original image
    and writing it to output file the remaining area is of black color.
    I want the background should be transparent.
    Code I'm using is not using JAI.
    Please suggest me the solution.
    the code I'm using is as follows:
    public static void makeThumbnail(String inFile, String thumbFile ) throws Exception {
    Image image = Toolkit.getDefaultToolkit().getImage(inFile);
    MediaTracker mediaTracker = new MediaTracker(new Container());
    mediaTracker.addImage(image, 0);
    mediaTracker.waitForID(0);
    int fixedHeight = 200 ;
    int fixedWidth = 200 ;
    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    double imageRatio = 0.25 ;     
    int thumbHeight = (int)(imageHeight * imageRatio );
    int thumbWidth = (int)(imageWidth * imageRatio );
    int x = ( fixedWidth - thumbWidth )/2 ;
    int y = ( fixedHeight - thumbHeight )/2 ;
    System.out.println(thumbHeight + " - " + y );
    System.out.println(thumbWidth + " - " + x );
    // draw original image to thumbnail image object and
    // scale it to the new size on-the-fly
    BufferedImage thumbImage = new BufferedImage(fixedWidth, fixedHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setColor( new Color( 255, 255, 255, 0) );
    int rule = AlphaComposite.SRC_IN ;
    AlphaComposite ac = AlphaComposite.getInstance(rule, 0.9f);
    graphics2D.setComposite(ac);
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, x, y, thumbWidth, thumbHeight, null);
    // save thumbnail image to OUTFILE
    BufferedOutputStream out = new BufferedOutputStream(new    FileOutputStream(thumbFile));
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
    int quality = 60 ;
    quality = Math.max(0, Math.min(quality, 100));
    param.setQuality((float)quality / 100.0f, false);
    encoder.setJPEGEncodeParam(param);
    encoder.encode(thumbImage);
    }

    Change this line
    BufferedImage thumbImage = new BufferedImage(fixedWidth, fixedHeight,
              BufferedImage.TYPE_INT_RGB);
    ...to use a BufferedImage type that supports transparency like TYPE_INT_ARGB or TYBE_4BYTE_ABGR (I would recommend the latter since your saving the image).
    Also, btw, you're not going to like the quality of the thumbnail if the image is reduced by more then half its size.

  • Convert colour images to grayscale images & get pixel data from them

    Is the code below correct to convert colour images to grayscale images in Java?
    public void convertToGrayscale (String sourceName,String destName) throws Exception {
    JPEGImageDecoder decoder=JPEGCodec.createJPEGDecoder(new FileInputStream(sourceName));
    JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(new FileOutputStream(destName));
    BufferedImage sourceImg=decoder.decodeAsBufferedImage();
    BufferedImageOp op =new ColorConvertOp(
              ColorSpace.getInstance(ColorSpace.CS_GRAY),null);
         BufferedImage destImg = op.filter(sourceImg,null);
    encoder.encode(destImg);
    decoder = null;
    encoder = null;
    When I get grayscale images from the code below, I would like to access the pixels of those images. So I tried to do:
    byte[] dd=((DataBufferByte)mImage.getRaster().getDataBuffer()).getData();
    BUT the data result array is not 0-255. Could anyone suggest how to obtain pixel data from grayscale images?
    In case that my code shown is not correct or suitable, please give your advice. What I would like to do are in the steps as follows:
    1 change 100*70 jpeg-images to 100*70 grayscale images.
    2 create two dimensional array of pixel data (example [100][70]) from converted images. The number in the array should be between 0-255, right??? And 0 refers to black colour and 255 refers to white colour???
    I am confused about grayscale images. Please help.
    Thank you so much

    I am not sure i understand what is the problem exactly.
    Structure of DataBuffer is described by SampleModel used by same Raster
    object. E.g. it might be 1 byte per xipex or 4 bytes per pixel.
    In your example convertToGrayscale saves images to file as JPEG and
    it seems you later read it back. It is possible what image you read back
    is not greyscale but ARGB and data buffer has different format.
    Technically, if you just need level of grey you may simply
    call getRGB on your output image. Grey is uniform mix of R, G and B.
    Also, instead of ColorConverOp you may dimply create output image of
    grayscale type and draw your color input image with drawImage().
    If none of these helps please try to provide more details.

  • How to get RGB value from pixel of an image.

    hi, i need a little help... Is there any EASY way to get RGB value from point of an image? I searched javadoc but i only found very complex getRGB method working only with regions, and saving data into arrays.
    Is there any other way that can use for example image.getGraphics() (so, i mean to get RGB from point of Graphics object) ?
    Btw.: If you know, how Sprite.collidesWith(Sprite s, Boolean pixellevel) is working (with pixellevel = true), please write me. It could solve my problem too.
    Thanks

    Is there any other way that can use for example image.getGraphics() (so, i mean to get RGB from point of Graphics object) ?You can think of the graphics object like a pencil or paintbrush. Does a paintbrush know the color of the surface it is painting on? No.
    Btw.: If you know, how Sprite.collidesWith(Sprite s, Boolean pixellevel) is working (with pixellevel = true), please write me. It could solve my problem too.Download the reference implementation from this site and see for yourself.
    luck, db

  • Getting a pixel between thumbnail images

    Hi Folks
    I am using a CellRenderer to display thumbnail images,and I want to
    keep a distance of 1 pixel between the images.
    What can I do to get this?
    Attached is my renderer
    public FTRDPictureChooserDateAndTimeCellRenderer(){
         thumbnailImage    = new JLabel();
         imageText         = new JLabel();
         dateAndTimeLabel  = new JLabel();
         gbl = new GridBagLayout();
         setLayout(gbl);
         gbc = new GridBagConstraints();
         gbc.gridx      = 0;       // x represents cols
         gbc.gridy      = 0;       // y represents rows
         gbc.gridwidth  = 1;               // reset to the default
         gbc.gridheight = 2;       // span 2 rows to display image.
         gbc.weighty    = 1.0;
         gbc.weightx    = 1.0;
         add(thumbnailImage,gbc);
         /* Image Name */
         gbc.gridwidth  = GridBagConstraints.REMAINDER; //end row
         gbc.gridheight = 1;     
         gbc.gridx      = 1;          
         gbc.gridy      = 0;
            add(imageText,gbc);                                                      
         setOpaque(true);
                                                                          

    Well, let's see... now if I look at the API docs for
    GridBagConstraints, I see it has fields: ipadx and
    ipady ... I wonder what they do?They pad inside the component so won't actually help. However, the insets field will allow you to define the number of pixels to pad outside the component. So you can either do gbc.insets = new Insets(0,0,0,1) from the first component or gbc.insets = new Insets(0,1,0,0) for the second one. Either will add a single pixel between them.
    Ian

  • Get binary from image

    I'm trying to get the binary pattern from an image and store it byte by byte, so i can manipulate it.
    Any help on how i would go about doing this would be greatfully recieved.
    Perhaps a url to some relevant material would be nice. Thought I'd come to the guys who know about this sort of thing.
    Thanks
    Fraser

    try {
                int[] pixels = new int[width * height];
                PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width);
                pg.grabPixels();
                return pixels;
            } catch (InterruptedException ie) { return null; }This code is an example using a pixel grabber to retrieve an array of int values, each representing pixel data.
    int values are 32 bit, but the pixel data should only encompass the first 8 bits of each int.
    You can't cast the int to a byte because it will chop off the bits from the other end leaving you with a byte full of 0's and a black image.
    To convert these ints to bytes you can use bitwise operators to chop off the leading 0 bits and then build a byte array with your image data.

Maybe you are looking for

  • How to print report on client default printer ?

    I develop web application. I use jdev 10.1.3.4.0 . I can print report in PDF format. My Problem I can't print report on client default printer. when Client run application and print. Report is printed at server default printer How can I do. _My sourc

  • TC Will Not Connect to Wired Devices

    I have a brand new Time Capsule.  All was working fine until this past weekend.  The problem is that I can only connect wireless devices now.  Wired devices do not seem to be recognized by the time capsule.  This is the case even for devices that hav

  • Updating transaction MD61 using information from inbound IDOC

    Is there any standard IDOC type for Planned Independent Requirement(having fields of table PBED and PBIM in its segment)?If such an IDOC type doesnt exist then i have to go for custom idoc type creation I have an inbound IDOC having 4 fields in its s

  • Being spammed by non-contacts even when resticted in settings..

    I am getting spam messages from people outside my contact list.  This despite having selected the option in the setting for this no to be allowed. What can I do..? Here is one: Hello Dear friend, God day with duo respect and humility, am presenting t

  • BT Hub 2 Handset

    This ones got me stumped! My handset wont work with the batteries in! I thought they were dead so put some new ones in, and still nada! put it on the hub or charger without batteries and it comes on with a flickering screen and battery full icon? any