Get an Image object

hello :)
My problem is that, i am trying to draw an image in a JPanel, but i cant get the object (Image) i want to use, cause i dont know if swing has any Image object creator like Applets getImage or Toolkit getImage.. and i want to do this without using Toolkit.getDefaultToolkit().geImage(URL)
Tank u for your help.

It is better to load images using .....getClass().getResource(....) i.e.
ImageIcon i = new ImageIcon(getClass().getResource(url));
With this approach the url can be CLASSPATH relative and the image can be in a jar (the same
jar as the class loading it).
Hope that helps you

Similar Messages

  • Iphone get photo as image object

    hi,
    I am new to Mac os programming. I am testing iphone programming. I would like to access the photo saved in iphone as an bitmap image object. How can I do it?
    I know I can use UIImagePickerController, but not sure how to get the image object and access every pixel after that.
    Thank you very mcuh.
    af

    The UIImagePickerControllerDelegate method didFinishPickingImage is called once the user chooses a photo. This contains the UIImage. UIImages can be converted
    http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImageP ickerControllerDelegateProtocol/UIImagePickerControllerDelegate/UIImagePickerControllerDelegate.html#// appleref/occ/intfm/UIImagePickerControllerDelegate/imagePickerController:didFinishPic kingImage:editingInfo:

  • How to get all images from folder in c#?

    I am trying to get all images from folder. But it is not executing from following:
     string path=@"C:\wamp\www\fileupload\user_data";
                string[] filePaths = Directory.GetFiles(path,".jpg");
                for (int i = 0; i < filePaths.Length; i++)
                    dataGridImage.Controls.Add(filePaths[i]);
    Please give me the correct solution.

    How to display all images from folder in picturebox in c#?
    private void Form1_Load(object sender, EventArgs e)
    string[] files = Directory.GetFiles(Form1.programdir + "\\card_images", "*", SearchOption.TopDirectoryOnly);
    foreach (var filename in files)
    Bitmap bmp = null;
    try
    bmp = new Bitmap(filename);
    catch (Exception e)
    // remove this if you don't want to see the exception message
    MessageBox.Show(e.Message);
    continue;
    var card = new PictureBox();
    card.BackgroundImage = bmp;
    card.Padding = new Padding(0);
    card.BackgroundImageLayout = ImageLayout.Stretch;
    card.MouseDown += new MouseEventHandler(card_click);
    card.Size = new Size((int)(this.ClientSize.Width / 2) - 15, images.Height);
    images.Controls.Add(card);
    Free .NET Barcode Generator & Scanner supporting over 40 kinds of 1D & 2D symbologies.

  • How to get the image stored in archieve link as an attachment in work item.

    Hi All,
    through transaction OAWD we are storing scanned images.
    Once this transaction is executed a workitem appears in the inbox of the initiator with the scanned invoice as attachment.
    When the user executes the work item FV60 screen is displayed where the user enters the data based on the scanned invoice attachment.
    After the user Parks the document the custom workflow triggers and a workitem appears in the inbox of an approver.
    Our requirement is that the scanned image should also appear as the attachment.
    Can you please suggest how to get the image stored in archieve link as an attachment in work item.
    Regards
    Shraddha

    Hi Martin,
    with every parked document a scanned image is linked.
    I need to create a link under objects and attachments in the work item, such that when the user clicks that link the image is displayed.
    At present the following functionality is available.
    The BO used is FIPP
    Objects and attachments:
    parkeddocument:AK0108500001252008.(via FIPP binding with WIOBJECT_ID)
    On clicking the link below objects and attachments: the parked document AK0108500001252008 opens in display mode.
    Now we want to have 2 links:
    parkeddocument:AK0108500001252008.
    image.
    When we click on the link image then the scanned invoice linked to the document should get opened.
    I am able to get the image id of the the image through  SAP_WAPI_GET__OBJECTS,
    export parameter leading_object provides the detail.
    But I am not able to figure out how to use it in my workflow to display it as an attachment.
    Hope this will give a better understanding of my question.
    can you please suggest as to how I should proceed with it.

  • How do you change the capture dimensions in the Get Panel Image VI

    My objective is to capture the front panel image to a JPEG file. I want to be able to alter the dimensions of Front Panel Image so I can exclude certain areas of the front panel. I am using the GET PANEL IMAGE.VI and the WRITE JPEG FILE.VI. I have tried using a Cluster structure from the bounds property of the GET PANEL IMAGE.VI to feed into the "rect" property of the WRITE JPEG FILE.vi however as soon as I alter the dimensions from the original dimensions it fails to save the panel image to file. Is this actually possible, or does LabVIEW restrict users from altering the panel capture dimensions? Or is this a known bug in LabVIEW v6.0?

    Hi,
    Here is a zip file containing two VIs.
    'Change Control Value.vi' when run will load the VI 'Demo.vi'. It will alter its size and the run demo.vi.
    On the front panel or demo.vi, press the Update button and the image will be written to c:\temp.
    All a bit crude but the mechanism works in labview 5.1.1. (Unfortunately I haven't got version 6.0.2 installed yet.)
    Regards
    Ray.
    Regards
    Ray Farmer
    Attachments:
    demo.zip ‏33 KB

  • How do i convert an image object to a byte array ?

    Hi
    how do i convert an image object into a byte array
    early reply apperciated

    Oh sorry my method and the other method need to have the pixels from the Image passed to them which you get my using pixelgrabber:
    //create width and height variables from image
              int w = img.getWidth(this);
              int h = img.getHeight(this);
              //retrive picture from image
              int[] pix = new int[w * h];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pix, 0, w);
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              }

  • Save an Image object into a XML text document

    ello:
    I have a problem with saving an image. I need to encapsulate it into two XML tags:
    <Image> xxxxxx </Image>
    The "xxxx" must be a String that represents my Image object.
    In J2ME I haven't serialization, and all the examples about "manual serialization" works with primitive types :(
    I've already read that I can do .getRGB() over my Image object, and obtain an array of int, wich represent each pixel. Ok, I can transform the array into a String, and write it in my XML text document, but later: how I obtain my array from that String?
    Thak you very much

    private Image img;
    byte rgb[] = null;
    private rgbLength; // get lenth of your string
    rgb = new byte(rgbLength);
    rgb = ... //load data from string to this array
    img = createRGBImage(rgb, int width, int height, false) ;You must know length of your string and must encapsulate in to XML width and height of this image;

  • How to display "Image" object in the browser?

    can anyone please tell me how can i display "Image" object in the browser?
    I have an image object that i retrieved from AS400 BLOB object by using toolbox.jar (for as400 access for java including all necessary classes like jdbc driver, security etc.).
    i want to display this object in the browser so i will be able to web-enable my BLOB objects stored on as400.thx...

    In your HTML:
    <img src="ImageServlet">
    In ImageServlet:
    Make calls to DB to get your image as byte array and store it in:
    byte[] buffer = new byte[imageSize];
    ServletOutputStream out = response.getOutputStream();
    for(int i = 0; i < imageSize; i++)
    out.write(buffer, i, 1);
    out.close();

  • Get newest image when using IMAQdx grab

    Hi everone!
    I have a problem. I use IMAQdx grab.vi to capture image from camera usb. it has 30 fps. I want to get newest image, which camera acquired. but I realize that IMAQdx grab.vi copys sequent image out of buffer. I simulate a moving rectangle. then I use camera to positive object. I alway receive position of object from camera delay 3 frame.I expect it to delay 1 frame. I attached my program. I want to configure camera to grab the newest image.
    Thank in advance!
    Attachments:
    MAIN.vi ‏204 KB

    The cleanest way to accomplish what you are trying to do uses the low-level functions. The Get Image VI will automatically pull the next buffer available, but can also be configured to pull the most recently acquired buffer or any buffer of your choosing. You can see the function's context help for more details.
    Also, if you are unfamiliar with using the low-level functions there is a very good example in the example finder called "Low-Level Grab" in the IMAQdx section.
    Christopher S. | Applications Engineer
    Certified LabVIEW Developer
    "If in doubt... flat out." - Colin McRae

  • Getting black image when resize to thumbnail

    When uploading images through a servlet via a webbrowser, I am saving the image to the harddrive and then resizing the image as thumbnail for certain view pages.
    I have tried serveral approaches to resizing the image, with all solutions I use the thumbnail image is being returned as a solid back image.
    I started with the example on the Sun Tech Tips site: http://java.sun.com/developer/TechTips/1999/tt1021.html
        public static void createThumbnail(
                String orig, String thumb, int maxDim) {
            try {
                // Get the image from a file.
                Image inImage = new ImageIcon(orig).getImage();
                // Determine the scale.
                double scale = (double) maxDim / (double) inImage.getHeight(null);
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) maxDim / (double) inImage.getWidth(null);
                // Determine size of new image. One of them
                // should equal maxDim.
                int scaledW = (int) (scale * inImage.getWidth(null));
                int scaledH = (int) (scale * inImage.getHeight(null));
                // Create an image buffer in which to paint on.
                BufferedImage outImage = new BufferedImage(scaledW, scaledH,
                        BufferedImage.TYPE_INT_RGB);
                // Set the scale.
                AffineTransform tx = new AffineTransform();
                // If the image is smaller than the desired image size,
                // don't bother scaling.
                if (scale < 1.0d) {
                    tx.scale(scale, scale);
                // Paint image.
                Graphics2D g2d = outImage.createGraphics();
                g2d.drawImage(inImage, tx, null);
                g2d.dispose();
                // JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(thumb);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
        }I have tried other approaches from various posting I found off google such as:
        public static void scale(String filename, String outputfile, int width, int height)
                throws Exception {
            ImageIcon source = new ImageIcon(filename);
            double sf_x = width / (double) source.getIconWidth();
            double sf_y = height / (double) source.getIconHeight();
            System.err.println("Scale_factor_X: " + sf_x);
            System.err.println("Scale_factor_Y: " + sf_y);
            BufferedImage bufimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufimg.createGraphics();
            g.setComposite(AlphaComposite.Src);
            AffineTransform aft = AffineTransform.getScaleInstance(sf_x, sf_y);
            g.drawImage(source.getImage(), aft, null);
            FileOutputStream os = new FileOutputStream(outputfile);
            JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(os);
            enc.encode(bufimg);
            os.flush();
            os.close();
        }No matter the implementation, the output is always the black image. I tried additional steps such as adding the JVM flag of:
    -Djava.awt.headless=true
    I've certainly spent a few hours on the google search engine and reviewing various newgroup posting, your suggestions come with many thanks.
    Cheers,
    Justen

    I tried your method and it worked okay. The only way I can get the black image is to send in a distorted path. One of the problems with the ImageIcon.getImage technique is that you get no feedback about loading failure. Here's a way to peek into the process for some indication of how it went. If you can tolerate j2se 1.4+ you could use the ImageIO methods in lieu of the proprietary JPGImageEncoder.
    import com.sun.image.codec.jpeg.*;
    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ImageScalingTest extends JPanel
        public static void createThumbnail(
                String orig, String thumb, int maxDim) {
            try {
                // Get the image from a file.
                ImageIcon icon = new ImageIcon(orig);
                int status = icon.getImageLoadStatus();
                String s = "";
                switch(status)
                    case MediaTracker.ABORTED:
                        s = "ABORTED";
                        break;
                    case MediaTracker.ERRORED:
                        s = "ERRORED";
                        break;
                    case MediaTracker.COMPLETE:
                        s = "COMPLETE";
                System.out.println("image loading status: " + s);
                Image inImage = icon.getImage();
    //            Object o = ImageScalingTest.class.getResource(orig);
    //            /*Buffered*/Image inImage = ImageIO.read(((URL)o).openStream());
                // Determine the scale.
                double scale = (double) maxDim / (double) inImage.getHeight(null);
                if (inImage.getWidth(null) > inImage.getHeight(null)) {
                    scale = (double) maxDim / (double) inImage.getWidth(null);
                // Determine size of new image. One of them
                // should equal maxDim.
                int scaledW = (int) (scale * inImage.getWidth(null));
                int scaledH = (int) (scale * inImage.getHeight(null));
                // Create an image buffer in which to paint on.
                BufferedImage outImage = new BufferedImage(scaledW, scaledH,
                        BufferedImage.TYPE_INT_RGB);
                // Set the scale.
                AffineTransform tx = new AffineTransform();
                // If the image is smaller than the desired image size,
                // don't bother scaling.
                if (scale < 1.0d) {
                    tx.scale(scale, scale);
                // Paint image.
                Graphics2D g2d = outImage.createGraphics();
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                     RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                g2d.drawImage(inImage, tx, null);
                g2d.dispose();
                // JPEG-encode the image and write to file.
                OutputStream os = new FileOutputStream(thumb);
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
                encoder.encode(outImage);
                os.close();
    //           ImageIO.write(outImage, "jpg", new File(thumb));
            } catch (IOException e) {
                e.printStackTrace();
        public static void main(String[] args)
            String path = "images/cougar.jpg";
            String fileName = "imageScalingTest.jpg";
            int size = 75;
            ImageScalingTest test = new ImageScalingTest();
            test.createThumbnail(path, fileName, size);
    }

  • Getting an image from a file

    I am trying to get an image from a file
    is there a way to convert a BufferedImage into an Image?
    or otherwise get an Image directly from a file?
    my searches turn up nothing
    TIA

    okay, so here's the new code:
    //  image_tracer.java
    //  image tracer
    //  Created by Erik Schmidt on 8/21/06.
    //  Copyright (c) 2006 __MyCompanyName__. All rights reserved.
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.io.*;
    import java.awt.image.*;
    import java.util.ArrayList;
    import java.awt.Graphics;
    import java.net.*;
    import java.applet.*;
    //FILE class, deals with File IO (note: does not possess the full method count of the java.io class File, this class only supports IO)
    class FILE {
         private static String fname=new String();
         //class constructor, takes a String as an argument, returns nothing
         public FILE(String fName){
              fname=fName;
         }//end constructor
         //gets filename, takes no argument, returns a String
         public static String getFilename(){ return fname; }
         //Reads in a file, takes no arguments, returns a String-either the contents of the file, or an error message
         public static String readFile() throws FileNotFoundException,IOException {
              String ret=new String();
              String tempstr=new String();
              File tFile=new File(fname);
              BufferedReader inFile=new BufferedReader(new FileReader(new File(fname)));
              if(tFile.exists()){
                   while((tempstr=inFile.readLine())!=null) ret+=tempstr+"\n";
                   ret=ret.substring(0,ret.length()-1);
              }else{
                   return null;
              }//end if
              return ret;
         }//end readFile
         //Writes to a file, takes a String as an argument, returns true for sucess; false for IOException
         public static boolean writeFile(String str) throws IOException{
              PrintWriter prnt=new PrintWriter(new FileWriter(fname,false),true);
              try{
                   prnt.println(str);
                   return true;
              }catch(Exception ioe){
                   return false;
              }//end try/catch
         }//end writeFile
         //Appends text to a file, returns true on completion; false on IOException
         public static boolean appendFile(String str) throws IOException{
              PrintWriter prnt=new PrintWriter(new FileWriter(fname,true),true);
              try{
                   prnt.println(str);
                   return true;
              }catch(Exception ioe){
                   return false;
              }//end try/catch
         }//end appendFile
         //Tells if file exists.  Takes no arguments, returns true if it exists, false if not
         public static boolean exists(){
              File tf=new File(fname);
              if(tf.exists()) return true;
              else return false;
         }//end exists
    }//end FILE class
    class MyPanel extends JPanel {
         Graphics save;
         Image blank;
         Image face;
         ArrayList x;
         ArrayList y;
         ImageObserver ob;
         private class MListen implements MouseMotionListener {
              public void mouseDragged(MouseEvent e){
                   x.add(new Integer(e.getX()));
                   y.add(new Integer(e.getY()));
                   repaint();
              public void mouseMoved(MouseEvent e){
                   //do nothing
         public MyPanel(Image f){
              x=new ArrayList();
              y=new ArrayList();
              blank=Toolkit.getDefaultToolkit().createImage("~/sites/blank.jpg");
              //save=createImage(500,500).getGraphics();
              face=f;
              addMouseMotionListener(new MListen());
              x.add(new Integer(-30));
              y.add(new Integer(-30));
         public void paintComponent(Graphics g){
              g.drawImage(face,0,0,ob);
              //save.drawImage(blank,0,0,ob);
              g.setColor(Color.black);
              //save.setColor(Color.black);
              for(int i=0;i<x.size();i++){
                   //save.fillOval(((Integer)x.get(i)).intValue(),((Integer)y.get(i)).intValue(),20,20);
                   g.fillOval(((Integer)x.get(i)).intValue(),((Integer)y.get(i)).intValue(),20,20);
    class WListen extends WindowAdapter {
         public void WindowClosed(WindowEvent e){
              System.exit(0);
    class MainFrame extends JFrame {
         MyPanel panel;
         JButton submit;
         JPanel main;
         public MainFrame(Image face){
              super("Image Tracer");
              setSize(750,750);
              panel=new MyPanel(face);
              submit=new JButton("Save");
              main=new JPanel(new BorderLayout());
              main.add(panel,BorderLayout.CENTER);
              main.add(submit,BorderLayout.SOUTH);
              setContentPane(main);
    class IMAGE {
         public Image run(String filename){
              return Toolkit.getDefaultToolkit().createImage(filename);
    public class image_tracer {
        public static void main (String args[]) {
              IMAGE image=new IMAGE();
              MainFrame frame=new MainFrame(image.run("~/sites/face.jpg"));
              frame.addWindowListener(new WListen());
              frame.show();
    }ignore the file stuff, that's for later
    why does MainFrame not display the MyPanel object?

  • Load jpg in image object

    Hi, i'm trying to create an image object from a jpg file:
    public static void main(String[] args)
    Image img;
    Toolkit t;
    t = Toolkit.getDefaultToolkit();
    img = t.getImage("C:\\Documents and Settings\\m.lipreri\\Desktop\\ciao.jpg");
    System.out.println("img: "+img.toString());
    Frame f = new Frame("Es1_Im");
    ImageFrame IM = new ImageFrame(f,img);
    IM.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    IM.setSize(500,400);
    IM.setVisible(true);
    class ImageFrame extends Frame{
    Frame f;
    Image im;
    //costruttore
    ImageFrame(Frame f,Image im){
    this.f = f;
    this.im = im;
    public void paint(Graphics g){
    g.drawImage(im,0,0,this);
    }but this code doesn't show me anithing in the applet, the image path is right, i've tried to past the path in my browser and i can see the image.
    thnx

    Images get loaded asynchronously, so the image
    probably isn't loaded completely when you try to
    display it. See java.awt.MediaTracker or use
    javax.swing.ImageIcon for loading.I could be wrong, but isn't that the ancient way of doing it? I haven't used MediaTracker in ages. Just use ImageIcon. It's the easist way I know to work with images.

  • Converting an Image object to a BufferedImage object?

    I have a BufferedImage object, bi, which I want to resize, hence:
    Image image = bi.getScaledInstance(400, 300, Image.SCALE_DEFAULT);
    Next I want to encode the resized image to JPEG format. The problem is that inorder to use the JPEGImageEncoder.encode() method, I need to pass it a BufferedImage object. I have looked through the API and cant see a way of converting the Image object to a BufferedImage object.
    Can anyone shed some light on this problem?
    Any help will be much appreciated.

    I copied + pasted the code from:
    http://java.sun.com/docs/books/tutorial/2d/problems/ind
    x.html :-)
    So you propably could use :
    int width = 400;
    int height = 300;
    Image image = bi.getScaledInstance(width, height,
    Image.SCALE_DEFAULT);
    BufferedImage bi = new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
    Graphics2D biContext = bi.createGraphics();
    biContext.drawImage(img, 0, 0, null);Greets
    PuceThis works fine; but has anybody else noticed this takes an unreasonable amount of time? How to get around this?

  • Image object compression

    How do I compress an image object?
    I need it to be fast, as I want to send it over the network using socket.
    I have already tried GZIP but got the error "Not in GZIP format".When I use GZIP the code runs for a while and then gives the error I stated above.
    I have also used Inflater and Deflater. It reduces the size of my image object but I did not get any improvement in speed.It is basically a code for bandwidth utilization.
    I need some help a.s.a.p.
    Thanks.

    bandwidth is not an issue now. I am actually doing a
    project on thin client and for my demo i need
    improvement in speed.1) If bandwidth not the issue, then don't use compression, since you don't need it (yet)
    2) I bet there are at least five other, more critical performance bottlenecks in your code
    3) Maybe you should think about your design. Why not give the processed data to the client and have it draw the image itself, instead of having the server creating the image and sending it to a client?
    Or are you trying to create some Citrix-Metaframe-like terminal?

  • Insert Image gets Placeholder Image

    Whenever I insert an image (either with the menu or the Insert bar icon), I get the placeholder image instead.
    I should be getting a file browser dialog, but I only get a 32x32 gray box. Maybe there is a preference somewhere that has changed?
    I am using Dreamweaver CS 5.5, on a Mac with os 10.8.2
    mark

    Are you clicking on 'Insert > Image Objects > Image Placeholder'? or 'Insert > Image'?
    Image placeholder will, by default, give you a 32px square placeholder.
    Placeholder
    Actual Image
    -ST

Maybe you are looking for

  • After Effects cs4 in Production Prem. fails to install

    I have Production Premium CS4 running on Windows 7.  I went back the other day to install the After Effects application.  Each time I try to install it, It does through the install process.  After it goes through disk #3, it stops and I get a message

  • Can't Turn Off Display Completely in XP

    Hi, My MacBook Pro screen does not turn off after idling in XP. I'd to be able to turn the display off (even manually) without putting the computer completely to sleep. When I dim the screen all the way down in XP, the lowest setting is not off, just

  • Lost network connection after SW update

    First time poster, relative newbie to Mac. I blindly updated to 10.4.11 and then found that my Mini had no network connection, yet my Ministack external FW HD and WinXP (thru BootCamp) will still connect wirelessly to my Westel router which has not b

  • Best SAP Training Institutes in Pune .. ?

    Hi Anyone Plz suggest which SAP Training Institutes in Pune is providing better placement Seed Infotech , Delphi or Lithan Genovate? I am willing to join for SAP ABAP. Also tell which is be better OLT or ILT? Also does bank loan option is there with

  • Why does FF newest version not work as a web browser?

    I updated to FF version 8 but the browser will not launch. I got an email from FF help telling me to uninstall FF then reinstall. I did this-- still useless. I checked my firewall and that's OK. So then I uninstalled FF 8 and went back to version 3.7