Image object getWidth() and getHeight() returning -1

Hello all,
I'm currently unit testing a pretty simple utility that calculates a new image position, given a handful of parameters (including image width and height).
The problem I'm running into is this:
The image width/height don't always load immediately. My only clue so far from searching the web is this:
http://download-llnw.oracle.com/javase/6/docs/api/java/awt/Image.html#getWidth%28java.awt.image.ImageObserver%29
which states Determines the width of the image. If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later. In my JUnit test harness, I have the following code to load my images, using Toolkit:
public static final String TEST_IMG_1_PATH = "images/apple_logo.png";
public static final String TEST_IMG_2_PATH = "images/dude.png";
private Image testImage1, testImage2;
@Before
public void setUp() throws Exception {
     testImage1 = Toolkit.getDefaultToolkit().getImage(TEST_IMG_1_PATH);
     testImage2 = Toolkit.getDefaultToolkit().getImage(TEST_IMG_2_PATH);
     // check the image size to see if they are fully loaded:
     System.out.println(testImage1.getWidth(null));
     System.out.println(testImage1.getHeight(null));
     System.out.println(testImage2.getWidth(null));
     System.out.println(testImage2.getHeight(null));
}Because the utility method I'm testing heavily depends on the image size, my tests intermittently fail. When I run this, I typically get -1 for all of the image dimension checks (see the above println()s).
-1
-1
-1
-1Even with these "-1" results, my test still passes... which means at some point before the test assert() statement executes, the images do become fully loaded.
My question is: What can I do to make sure my image is loaded fully before I do anything with it? Is there any elegant way to handle this? Am I doing something wrong?
Thanks for your time.
-Thok

[http://forums.sun.com/thread.jspa?threadID=5446922]
db

Similar Messages

  • Getwidth() and getheight()

    I am very new to J2ME.
    I am writing a midlet that needs to find the width and height of the device screen, i have already got a part of the program that queries whether the device supports colour graphics and how much memory it has but this is done within the display class and the getwidth()and getheight() commands need to be used within the canvas class. Can anyone give me some tips as to how to implement this.
    Thanks for any help.
    Phil

    use this code:
    class DummyCanvas extends Canvas {
    protected void paint( Graphics g ){
    m_screenHeight = getHeight();
    m_screenWidth = getWidth();
    display.setCurrent( mClass.m_MainForm );
    hope that helps.

  • Problems with getWidth() and getHeight() in class Canvas

    Hi,
    i am developing MIDlets with Sun Studio4 One Update1 (Mobile Edition). Here is a simple example Code for my Problem:
    class MyCanvas extends Canvas
        public void paint(Graphics g)
            //Clear the Display
            g.setColor(0,0,0); //black
            g.fillRect(0,0,getWidth(),getHeight());
    }If i try to execute the Program with the Default Color Phone emulator included with Suns WTK2.0, everything works fine. (Ive tried to print out the results of getWidth() and getHeight() on the console, everything ok, the Displays width and height is displayed.).
    The problem is, that any other emulator from WTK1.0.4_01 (included with Sun Studio4 ME) compiles and preverifies fine, but while running the application, the emulator quits with the following error:
    ALERT: No such method getWidth.()I
    Execution completed successfully
    Anyone has an idea?
    Thanks!!

    Hello,
    I'm having the exact same problem and I'd like to know what changes you made to your code to get it working. My class is not an inner class and is very much like yours and so follows the form:
    class MyCanvas extends Canvas{ 
    int element = getWidth()/10;
    public void paint(Graphics g) {        //Clear the Display  
    g.setColor(0,0,0); //black
    g.fillRect(0,0,getWidth(),getHeight());
    I am also using WTK104. I did not have this problem until I renamed my file. I carried the renaming throughout the rest of the file in a consistent fashion and I don't see any problems with it. Any help appreciated.

  • Java.awt.Image getWidth() and getHeight() not working!

    Right- this is want I want to do.
    I have a background image which is added as a background image to a third party API class which extends Java.awt.Container. Such container is then added to the Content Pane of MyClass (which extends JFrame)
    I want to read the width and height of the image and resize MyClass accordingly.
    Problem is calling theImage.getWidth(MyClass.this) or theImage.getWidth(theThirdPartyAPIContainer) always return -1 and -1 denoting that no information is available.
    What do I need to do to obtain the height and width?

    Post here, cos don't know your email.
    Anyway
    - Can't use setPreferredSize because the Conatiner which is added to the ContentPane is a Awt Component not a Swing JComponent!
    - Also, the background is added AFTER the this.pack()and this.show().
    -I figured out that I could access Insets.top, Insets.left, Insets.right, Insets.bottom.
    I have basically the following
    |JMenuBar |
    L____________________________________________|
    | |
    | |
    | |
    | Third Party Class extending java.awt.Container |
    | containing an image of known size |
    | |
    L____________________________________________|
    I am fine for the width I do
    Insets frameInsets = this.getInsets();
    width = image.getWidth() + frameInsets.left + frameInsets.right;
    Height is the problem
    After some Trial an error it LOOKS on Solaris as if the following is right-
    height = image.getHeight()+frameInsets.top+ myJMenuBar.getSize()+getHeight+ myJMenuBar.getInsets().top + myJMenuBar.getInsets().bottom
    I cannot comprehend whether this is just a coincidence or not as I don't know why frameInsets.bottom should in any case be excluded.
    Here are the dimensions-
    frameInsets.left = 6
    frameInsets.right= 6
    frameInsets.top =28
    frameInsets.bottom = 6
    JMenuBar height = 23
    JMenuBar's Insets.top = 1
    JMenuBar's Insets.bottom = 1
    What should be the 'correct' calculations and does the Insets for the JMenuBar and the JFrame overlaps?

  • GetWidth() and getHeight() weird behaviour?

    Okay guys, what am i doing wrong here.
    Group myGroup;
    Label CompassLabel;
    //  doing new for all.
    //add label to the group.
    myGroup.getChildren().add(CompassLabel);
    CompassLabel.setText("360");So i have a label and add it to a group.
    Then i do this:
    System.out.println(CompassLabel.getWidth() + CompassLabel.getHeight());both return the value 0.0
    if i do this:
    Node nodeN = myGroup.getChildren().get(0); //The Label
    if (nodeN instanceof Label)
                            Label label = (Label) nodeN;
                            System.out.println(label.getWidth() + label.getHeight());
    }it gives:
    26.27734375 // Returned Value for width
    32.27734375 // returned Value for heightWhy is that? Thanks, regards.

    Hey Thanks.
    I can see the label on my Scene, so it's there.
    And between my first output and the second is like no other code.
    And it's pretty much the same object, isn't it?
    Can you give me some functions to check if there is something wrong?
    Can give you more code tho.
    public ViewPort()
            Compass              = new Circle();
            LineGroup           = new Group();
            LineGroup.getChildren().add(Compass);
            getChildren().add(LineGroup);
            for(int i = 15; i < 375;)
                CompassLine = new Line();
                CompassLabel = new Label(Integer.toString(i));
                LineGroup.getChildren().add(CompassLine);
                LineGroup.getChildren().add(CompassLabel);
                xStart = Compass.getCenterX() + ((Compass.getRadius() - 30) * Math.sin( i * ((2 * Math.PI) / 360)) );
                xStart2 = Compass.getCenterX() + ((Compass.getRadius() - 15) * Math.sin( i * ((2 * Math.PI) / 360)) );
                CompassLine.setStartX(xStart2);
                yStart = Compass.getCenterY() - ((Compass.getRadius() - 30) * Math.cos( i * ((2 * Math.PI) / 360)) );
                yStart2 = Compass.getCenterY() - ((Compass.getRadius() - 15) * Math.cos( i * ((2 * Math.PI) / 360)) );
                CompassLine.setStartY(yStart2);
                xEnd = Compass.getCenterX() + (Compass.getRadius() * Math.sin(i * ((2 * Math.PI) / 360)) );
                CompassLine.setEndX(xEnd);
                yEnd = Compass.getCenterY() - (Compass.getRadius() * Math.cos(i * ((2 * Math.PI) / 360)) );
                CompassLine.setEndY(yEnd);
                CompassLabel.setLayoutX(xStart - (CompassLabel.getWidth() / 2));
                CompassLabel.setLayoutY(yStart - (CompassLabel.getHeight() / 2));
    * Below it gives 0.0
                Node myNode = CompassLabel;
                Label myLabel = (Label) myNode;
                System.out.println(myLabel.getWidth() + myLabel.getHeight());
                i = i + 15;
            (TrainingsAnimation.getInstance().radarStage.widthProperty()).addListener(new ChangeListener()
                @Override
                public void changed(ObservableValue arg0, Object arg1, Object arg2)
                     newStageWdith.set(getWidth());
                     Compass.setCenterX(newStageWdith.getValue() / 2);
                     Compass.setRadius(TrainingsAnimation.getInstance().radarStage.getWidth() / 2 );
            (TrainingsAnimation.getInstance().radarStage.widthProperty()).addListener(new ChangeListener()
                @Override
                public void changed(ObservableValue arg0, Object arg1, Object arg2)
                    newStageHeight.set(getHeight());
                    Compass.setCenterY(newStageHeight.getValue() / 2);
                    for(int i = 0; i < LineGroup.getChildren().size(); i++)
                        Node nodeN = LineGroup.getChildren().get(i);
                        if (nodeN instanceof Line)
                            // Set new points for Line(actLine);
                            actLine++;
                            alpha = actLine * 15;
                            Line line = (Line)nodeN;
                            xStart = Compass.getCenterX() + ((Compass.getRadius() - 30) * Math.sin( alpha * ((2 * Math.PI) / 360)) );
                            xStart2 = Compass.getCenterX() + ((Compass.getRadius() - 15) * Math.sin( alpha * ((2 * Math.PI) / 360)) );
                            line.setStartX(xStart2);
                            yStart = Compass.getCenterY() - ((Compass.getRadius() - 30) * Math.cos( alpha * ((2 * Math.PI) / 360)) );
                            yStart2 = Compass.getCenterY() - ((Compass.getRadius() - 15) * Math.cos( alpha * ((2 * Math.PI) / 360)) );;
                            line.setStartY(yStart2);
                            xEnd = Compass.getCenterX() + (Compass.getRadius() * Math.sin(alpha * ((2 * Math.PI) / 360)));
                            line.setEndX(xEnd);
                            yEnd = Compass.getCenterY() - (Compass.getRadius() * Math.cos(alpha * ((2 * Math.PI) / 360)) );
                            line.setEndY(yEnd);
                        else if (nodeN instanceof Label)
                            Label label = (Label)nodeN;
                            label.setLayoutX(xStart - (label.getWidth() / 2) ) ;
                            label.setLayoutY(yStart - (label.getHeight() / 2) );
    * here are the correct height and width
                            System.out.println(label.getWidth() + label.getHeight());
                    Compass.setRadius(TrainingsAnimation.getInstance().radarStage.getHeight() / 2 );
        }Think this is to confusing and unclear to read, but maybe you see the mistake. i wrote a comment on the two ouputs.

  • Image.getWidth(ImageObserver obs) returns -1

    hello everyone i have used following code to load an image
    URL location=Sprite.class.getClassLoader().getResource(path);
        img=Toolkit.getDefaultToolkit().getImage(location);and this code to draw an image:
    g2d.drawImage(img, x, y, this);now i need to know the width and height of image for detecting collision.
    getWidth() and getHeight() returns -1.
    System.out.println(img.getWidth(this));my images are getting displayed in the frame.but when i try to access width and height of an image then it returns -1 which means width and height of image is not known yet.
    help !!
    thanks.

    sorry.
    This problem is in my game code.Since the code is very long so i am giving a small code reflecting my problem
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.net.URL;
    import javax.swing.*;
    import java.awt.Graphics;
    public class Sprite extends JPanel
    private JFrame frame;
    private Image img;
    public Sprite()
    frame=new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500,400);
    frame.getContentPane().add(this);
    frame.setVisible(true);
    URL location=Sprite.class.getClassLoader().getResource("small.jpg");
    img=Toolkit.getDefaultToolkit().getImage(location);
    this.repaint();
    System.out.println(img.getWidth(null));
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    public static void main(String[] args)
    new Sprite();
    }So i want the width and height of an image.But when i try to get it, it just returns -1 which means width and height is not known yet, according to java doc.
    if i use img=new ImageIcon("small.jpg").getImage() to load an image and if i access the width and height of an image using img.getWidth(ImageObserver obs) then i get correct value of width and height.
    i want to use above code that i provided to load an image.So pls help me out.Why it is returning -1 ?.
    Edited by: JGarage on Dec 6, 2008 7:59 AM
    Edited by: JGarage on Dec 6, 2008 8:00 AM

  • I am trying to batch convert cr2 to jpg. in bridge i go tools ps image processor and it returns a message "Image Processor.jsx could not be found." I updated cc to no avail. i am on mac 10.7.5

    I am trying to batch convert cr2 to jpg. in bridge i go tools>ps>image processor and it returns a message "Image Processor.jsx could not be found." I updated cc to no avail. i am on mac 10.7.5

    I go to file scripts but there is no option there for Image Processor

  • Picking up image drawan on panel into image object and saving itto file.

    hi dear friends,
    please help me out , My problem is:
    On challan generation screen we want to make provision for signeture.So for that purpose we have placed panel inside the frame where user can do the signeture.
    Signeture drawing is working .But now the next step is that i want to store it in a file(I mean to say whatever drawn on panel) so that that file can be saved in database and later on it can be retrived when ever required.
    will be thankful if anyone helps me.
    waiting for replays.

    try to use following code :
    BufferedImage im = new BufferedImage(comp.getWidth(), comp.getHeight(), BufferedImage.TYPE_INT_RGB);          
                             Graphics2D g2 = im.createGraphics();
                             //you may want to set background color, etc...     
                             comp.paint(g2);          
                             try          
                                  GIFEncoder gif = new GIFEncoder(im);
                                  gif.Write(new FileOutputStream(file));
                             catch(Exception e)          
    GifEncoder can be obtained from net. if u want i can mail u also.

  • Image repaint preformance and threading

    Folks,
    I'm trying to make this sucker run faster.
    My question is, can anyone please guide me, especially with regards synchronising the Threads more efficiently... I'm thinking of using join and i]notify to make the "navigator" threads yield to the swing threads, to give it a chance to repaint before continuing... does this sound sane to you?
    Currently, without the thread.sleep it paints get the first "burst", and then nothing until the alrorithm has completed... exactly not what I wanted, because the whole point of this GUI is to watch the algorithm at work... sort of a "visual debugger"... I find that watching an algorithm play out helps me to "imagineer" ways of improving it... and in this case improvement means optimisation... it's all about getting from A-J faster than anyone else on the planet, especially those smarty-wishbone-legs C# programmers ;-)
    The code is too big to post (darn that 7500 char limit!) so I'll split it over several posts here, and I've also posted it as a single download to [MazeOfBoltonGUI2.java|http://groups.google.com/group/comp_lang_java_exchange/web/MazeOfBoltonGUI2.java] on my google group (comp lang java exchange).
    Cheers all. Keith.
    package forums.maze;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.SortedMap;
    import java.util.TreeMap;
    import java.util.Stack;
    import java.util.Queue;
    import java.util.PriorityQueue;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    * A Visual debugger,
    * for the [A* Alogorithm|http://en.wikipedia.org/wiki/A*_search_algorithm] navigator
    * of the [Maze Of Bolton|http://cplus.about.com/od/programmingchallenges/a/challenge12.htm]
    * as implemented by [Prometheuz|http://forums.sun.com/profile.jspa?userID=550123]
    * with GUI by [Kajbj|http://forums.sun.com/profile.jspa?userID=91610]
    * hacked together by [Keith Corlett|http://forums.sun.com/profile.jspa?userID=640846]
    * and posted on [Sun's Java Forum|http://forums.sun.com/thread.jspa?threadID=5319334]
    * and posted on [Google news group|http://groups.google.com.au/group/comp_lang_java_exchange/]
    public class MazeOfBoltonGUI2
      static final char[][] matrix = readMatrix("map.txt");
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                MazeNavigator navigator = new MazeNavigator(matrix);
                JFrame frame = new JFrame("MazeOfBoltonGUI2");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new MainPanel(navigator));
                frame.pack();
                frame.setVisible(true);
              } catch (Exception e) {
                e.printStackTrace();
       * Reads the file into a char matrix[rows,cols] ie: an array of char arrays.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      private static char[][] readMatrix(String filename) {
        try {
          BufferedReader input = null;
          try {
            input = new BufferedReader(new FileReader(filename));
            char[][] matrix = null;
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ( (line = input.readLine()) != null ) {
              lines.add(line);
            int rows = lines.size();
            matrix = new char[rows][];
            for (int i=0; i<rows; i++) {
              matrix[i] = lines.get(i).toCharArray();
            System.err.println("DEBUG: rows="+rows+", cols="+matrix[0].length);
            return matrix;
          } finally {
            if(input!=null)input.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new IllegalStateException("Failed to readMatrix!", e);
    class MainPanel extends JPanel
      private static final long serialVersionUID = 1L;
      // button panel
      private final JButton goButton;
      // maze panel
      private final MazeNavigator navigator;
      private final Monitor<Path> monitor;
      private BufferedImage background;
      private BufferedImage image;
      private List<Path>currentPaths;
      public MainPanel(MazeNavigator navigator) {
        this.navigator = navigator;
        this.monitor = new SwingMonitor();
        this.goButton = new JButton("Go");
        goButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              final String caption = goButton.getText();
              goButton.setVisible(false);
              monitor.execute();
        add(goButton);
        setPreferredSize(new Dimension(navigator.maze.cols*3, navigator.maze.rows*3)); //w,h
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      private static Color[][] mazeColors;
      private static Color[][] createMazeColors(Maze maze) {
        Color[][] colors = new Color[maze.rows][maze.cols];
        for (int r=0; r<maze.rows; r++) {
          for (int c=0; c<maze.cols; c++) {
            colors[r][c] = getColor(maze.matrix[r][c].ch);
        return colors;
      }*... PTO ...*

    I'm persuaded that the main issue (no intermediate results drawn) is the improper use of SwingWorker.
    When you've got over it, you may want to consider other smaller-effect optimizations:
    Reconsider usage of an offscreen image*
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      }At first I didn't get why you wanted to draw an offscreen image, then paint it to the screen, all that in the EDT.
    After reading the draw() method more closely, I guess you want to ease the coding of the scaling: you draw an image where one cell = one pixel, then paint the image, scaled to the panel's display size.
    In terms of performance, I don't know how it stands:
    On one hand, the image creation if lighter (1 pixel per cell). And you have a point that the built-in scaling offered by Graphics2D.drawImage(image, size) may be efficient. I can't comment on that, I hope the granphics and hardware acceleration folks will pop in the thread.
    On the other hand, if the built-in scaling had poor performance, it may be good to try what "manual" scaling would bring you. That means, in a simplified version, skip the offscreen image creation, and draw directly on the paintComponent()'s Graphics2D argument. the drawing of a cell at coordinates c,r, for example, would look like:
    g.fillRect(c*CELL_WIDTH, r*CELL_HEIGHT, WIDTH, HEIGHT);Performance apart, the scaling as you do it currently has functional drawbacks, if you want pathes as 1-pixel width lines over large cells:
    - if the maze is smaller (in rows, columns) than the panel displaying it (in pixels), the cells will be scaled but the pathes too: so your 1-pixel lines appear as large as the cells. May or may not be a desired effect.
    - if the maze is larger than the display panel, the cells are shrinked, fine, but the so are the path lines, to a point where they may be invisible (probably depending on color blending, I'm a n00b at graphics operations).
    But maybe I misunderstood the need, and maybe the intended drawing of a path is actually the drawing of the rectangles of all its traversed cells, in special path colors?
    Reconsider intermediate allocations*
    Each paintComponent() call results in the allocation of a 2D-array of Color objects (method createMazeColors(Maze)).
    I don't see what the mazeColors array brings you. I assume you wanted to decouple the determination of colors (depending on cell state) and the rendering of the colors: what does it bring: no performance advantage (on the contrary, it adds a 2D array allocation, and 2xN^2 2D-array access), and does not improve the code readability either (subjective rant, sorry).
    Why don't you pass the Maze as an argument to the draw() method, and call the getColor(cell.ch) from there?
    Side note, maybe a bit subjective: performance apart, the design of the usage of this mazeColor array is a no-go!
    An instance method alters a static variable reference,which is used subsequently in another instance method, with no synchronization. The current code does that in a single thread (+paintxxx()+ is only called in the EDT), which keeps that safe (I'd dare to say: by luck), but considerations exposed below may have you refactor the design to introduce other threads, and may exhibit the thread-unsafety of this design.
    Consider drawing the image in a background thread.*
    Indeed the technique of drawing to an offscreen image is quite common, but it is often done to improve responsiveness (not raw performance) of Swing applications. Here is a resource about this (what the author calls the passive approach), although it doesn't use a background thread.
    The idea is that if a paintCompobnent() methods involves lots of computation (arithmetics of traversing a 2D model, scaling things, etc.), this takes CPU times in the EDT, and all subsequent events (such as, a MouseEvent, but also other painting events) keep pending on the event queue, which is consumed by the single event-dispatch thread. The result is that the UI appear unresponsive, and painting of other areas may seem hung.
    The idea is to move the computation to a background thread, which posts rendering to the EDT when the Image is ready to be displayed.
    Of course this doesn't gain any CPU time. This only ensures the EDT uses a minimal part of this CPU (only render and image and process events), instead of performing the whole computation.
    In your case you already have a background thread, and indeed an appropriate choice, a SwingWorker. The application of this technique would consist in calling the draw() method in the worker thread (in the update(Path) method), and invoke super.publish() only after the image has been updated. Note that the process(List<Path>) could then ignore its argument (you may reconsider the choice of type parameter of the worker), and simply get the latest version of the image attribute).
    Of course in this technique, the offscreen image filling is called synchronously from the Navigator, so this halts the algorithm part itself, for the duration of the image generation. You may refine the technique by spawning a dedicated thread for the image generation - with subtle guard code to handle occasions when the algorithm goes faster than the image generation, and posts a new update(Path) while the image generation for the previous path has not completed yet...
    Recuce the number of things to redraw*
    Two parts:
    first, depending on the number of cells and pathes, there may be (yet another) optimization, to not redraw the whole offscreen image, but only the cells/path that have changed in the last update(). In particular, if a path is not a line but a list of cells, then it's quite easy, reusing the current offscreen image, to only fillRect(...) the appropriate cells.
    Second, if a path is not rendered as a thin line over larger cells, but as cells themselves rendered in special path colors, you may paint cells and path in one go: instead of drawing, first the cells, then the path, draw only the cells, electing the color using a decision method such as:
    private Color getColor(Cell) {
        if (cell.getPathState()!=NOT_IN_ANY_PATH) {
            return getColor(cell.getPathState());
        else {
            return getColor(cell.ch);
    }Of course this forces you to modify your data model, and update the new pathState as part of the algorithm (or better isolated, in the update(Path) method, before invoking the drawing machinery). Maybe that was the intention of the mazeColors array?
    I haven't studied your other posts on the logic of the MazeOfBolton algorithm, so I don't know if it's acceptable for you that a cell appear to have only one path state, as opposed to one for each of the pathes that traverse it. This last trick may then seem incorrect, but please consider it as only a graphical information, and indeed your current image drawing draws only ONE path for a given cell (the last path in currentPaths that traverses this cell ).

  • Help! Saving an image to stream and recreating it on client over network

    Hi,
    I have an application that uses JDK 1.1.8. I am trying to capture the UI screens of this application over network to a client (another Java app running on a PC). The client uses JDK 1.3.0. As AWT image is not serializable, I got code that converts UI screens to int[] and persist to client socket as objectoutputstream.writeObject and read the data on client side using ObjectInputStream.readObject() api. Then I am converting the int[] to an Image. Then saving the image as JPEG file using JPEG encoder codec of JDK 1.3.0.
    I found the image in black and white even though the UI screens are in color. I have the code below. I am sure JPEG encoder part is not doing that. I am missing something when recreating an image. Could be colormodel or the way I create an image on the client side. I am testing this code on a Win XP box with both server and client running on the same machine. In real scenario, the UI runs on an embedded system with pSOS with pretty limited flash space. I am giving below my code.
    I appreciate any help or pointers.
    Thanks
    Puri
         public static String getImageDataHeader(Image img, String sImageName)
             final String HEADER = "{0} {1}x{2} {3}";
             String params[] = {sImageName,
                                String.valueOf(img.getWidth(null)),
                                String.valueOf(img.getHeight(null)),
                                System.getProperty("os.name")
             return MessageFormat.format(HEADER, params);
         public static int[] convertImageToIntArray(Image img)
             if (img == null)
                 return null;
            int imgResult[] = null;
            try
                int nImgWidth = img.getWidth(null);
                int nImgHeight = img.getHeight(null);
                if (nImgWidth < 0 || nImgHeight < 0)
                    Trace.traceError("Image is not ready");
                    return null;
                Trace.traceInfo("Image size: " + nImgWidth + "x" + nImgHeight);
                imgResult = new int[nImgWidth*nImgHeight];
                PixelGrabber grabber = new PixelGrabber(img, 0, 0, nImgWidth, nImgHeight, imgResult, 0, nImgWidth);
                grabber.grabPixels();
                ColorModel model = grabber.getColorModel();
                if (null != model)
                    Trace.traceInfo("Color model is " + model);
                    int nRMask, nGMask, nBMask, nAMask;
                    nRMask = model.getRed(0xFFFFFFFF);
                    nGMask = model.getRed(0xFFFFFFFF);
                    nBMask = model.getRed(0xFFFFFFFF);
                    nAMask = model.getRed(0xFFFFFFFF);
                    Trace.traceInfo("The Red mask: " + Integer.toHexString(nRMask) + ", Green mask: " +
                                    Integer.toHexString(nGMask) + ", Blue mask: " +
                                    Integer.toHexString(nBMask) + ", Alpha mask: " +
                                    Integer.toHexString(nAMask));
                if ((grabber.getStatus() & ImageObserver.ABORT) != 0)
                    Trace.traceError("Unable to grab pixels from the image");
                    imgResult = null;
            catch(Throwable error)
                error.printStackTrace();
            return imgResult;
         public static Image convertIntArrayToImage(Component comp, int imgData[], int nWidth, int nHeight)
             if (imgData == null || imgData.length <= 0 || nWidth <= 0 || nHeight <= 0)
                 return null;
            //ColorModel cm = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000);
            ColorModel cm = ColorModel.getRGBdefault();
            MemoryImageSource imgSource = new MemoryImageSource(nWidth, nHeight, cm, imgData, 0, nWidth);
            //MemoryImageSource imgSource = new MemoryImageSource(nWidth, nHeight, imgData, 0, nWidth);
            Image imgDummy = Toolkit.getDefaultToolkit().createImage(imgSource);
            Image imgResult = comp.createImage(nWidth, nHeight);
            Graphics gc = imgResult.getGraphics();
            if (null != gc)
                gc.drawImage(imgDummy, 0, 0, nWidth, nHeight, null);       
                gc.dispose();
                gc = null;       
             return imgResult;
         public static boolean saveImageToStream(OutputStream out, Image img, String sImageName)
             boolean bResult = true;
             try
                 ObjectOutputStream objOut = new ObjectOutputStream(out);
                int imageData[] = convertImageToIntArray(img);
                if (null != imageData)
                    // Now that our image is ready, write it to server
                    String sHeader = getImageDataHeader(img, sImageName);
                    objOut.writeObject(sHeader);
                    objOut.writeObject(imageData);
                    imageData = null;
                 else
                     bResult = false;
                objOut.flush();                
             catch(IOException error)
                 error.printStackTrace();
                 bResult = false;
             return bResult;
         public static Image readImageFromStream(InputStream in, Component comp, StringBuffer sbImageName)
             Image imgResult = null;
             try
                 ObjectInputStream objIn = new ObjectInputStream(in);
                 Object objData;
                 objData = objIn.readObject();
                 String sImageName, sSource;
                 int nWidth, nHeight;
                 if (objData instanceof String)
                     String sData = (String) objData;
                     int nIndex = sData.indexOf(' ');
                     sImageName = sData.substring(0, nIndex);
                     sData = sData.substring(nIndex+1);
                     nIndex = sData.indexOf('x');
                     nWidth = Math.atoi(sData.substring(0, nIndex));
                     sData = sData.substring(nIndex+1);
                     nIndex = sData.indexOf(' ');
                     nHeight = Math.atoi(sData.substring(0, nIndex));
                     sSource = sData.substring(nIndex+1);
                     Trace.traceInfo("Name: " + sImageName + ", Width: " + nWidth + ", Height: " + nHeight + ", Source: " + sSource);
                     objData = objIn.readObject();
                     if (objData instanceof int[])
                         int imgData[] = (int[]) objData;
                         imgResult = convertIntArrayToImage(comp, imgData, nWidth, nHeight);
                         sbImageName.setLength(0);
                         sbImageName.append(sImageName);
            catch(Exception error)
                error.printStackTrace();
             return imgResult;
         }   

    While testing more, I found that the client side is generating color UI screens if I use JDK 1.3 JVM for running the server (i.e the side that generates the img) without changing single line of code. But if I use JDK 1.1.8 JVM for the server, the client side is generating black and white versions (aka gray toned) of UI screens. So I added code to save int array that I got from PixelGrabber to a text file with 8 ints for each line in hex format. Generated these files on server side with JVM 1.1.8 and JVM 1.3. What I found is that the 1.1.8 pixel grabber is setting R,G,B components to same value where as 1.3 version is setting them to different values thus resulting in colored UI screens. I don't know why.

  • 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");
              }

  • Outputting an Image object to jpg or png

    Hello,
    I have an Image object in my code that is output from another java object. The other java object is from a libarary of GIS classes known as JLOOX.
    Anyway, I have an Image stored in the Image object but want to output it to a file. I was looking at the Java Almanac and saw a page http://javaalmanac.com/egs/javax.imageio/Graphic2File.html However, this uses a BufferedImage object.
    Is there anything I can do with the Image object to output to a file? Can I convert it to a BufferedImage somehow?

    BufferedImage b = new BufferedImage(
    source.getWidth(), source.getHeight(),
    BufferedImage.TYPE_INT_ARGB  );
    b.getGraphics().drawImage( 0, 0, source, null );
    ImageIO.write( b, "png" );Thanks, but I have an Image object. How do I write the Image object to ImageIo.write?

  • Catch the image of JTree and save it as a file

    There is an JTree and it has a few nodes.
    And there, I want to capture both the image of JTree and
    the images of it's child nodes as they show in screen.
    if possible, I want to capture image of all expanded nodes in tree and
    save them as jpg file.
    I try to capture the Image of JTree from JTree.createImage() method.
    and I also tried to capture the images of child nodes
    from JTree.getComponents() and capture images all of child nodes as they were.
    I,however,get to know the method
    Component.createImage() doesn't return the image that shows in screen as it was.
    could anybody tell me the answer?

    Hi,
    don't know if I got you right, but what you want is a "screenshot" of the JTree, right ?
    Try to paint the JTree in a BufferedImage and encode this as JPEG or whatever.
    BufferedImage theImage = new BufferedImage(
          owner.getWidth(), owner.getHeight(), BufferedImage.TYPE_INT_RGB);
          Graphics g = theImage.createGraphics();
          g.setClip( 0, 0, owner.getWidth(), owner.getHeight());
          owner.paint( g);owner is your JTree or any other component you want.
    Hope that helped.

  • Image select, resize and locally store (flex3 air example)

    Hi there,
    After a few days of struggling with images, resize functions
    and file dialog boxes I created a nice example application that
    shows how you can select an image, resize it and save the resized
    image in the application storing directory.
    I hope you can profit from it.
    Greets, jacob
    example code for flex 3 air.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="
    http://www.adobe.com/2006/mxml"
    layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.graphics.codec.PNGEncoder;
    public var imageFile:File;
    public var fileresultimage:Object;
    public var fileresultlabel:Object;
    // File.applicationStorageDirectory gets you to the local
    storage dir
    //On Windows, this is the "projectname" directory
    //(for example, C:\Documents and Settings\application
    data\projectname).
    // On Mac OS, it is /Users/userName/Documents.
    public var docsDir:File = File.applicationStorageDirectory;
    public function
    imageFileDialog(image:Object,label:Object):void
    fileresultimage=image;
    fileresultlabel=label;
    var imagesFilter:FileFilter =
    new FileFilter("Foto (*.jpg, *.gif, *.png)",
    "*.jpg;*.gif;*.png");
    if(imageFile==null)
    imageFile = new File();
    imageFile.addEventListener(Event.SELECT, imageSelected);
    imageFile.browseForOpen("Select an Image",[imagesFilter]);
    // if there is a file selected
    public function imageSelected(event:Event):void
    var newFile:File = event.target as File;
    //if there is a file object on the screen
    if(fileresultimage!=null)
    fileresultimage.source=imageFile.url;
    //if there is a label object on the screen
    if(fileresultlabel!=null)
    fileresultlabel.text=imageFile.url;
    if (newFile.exists==true)
    var loader:Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,
    handleImageComplete);
    loader.load(new URLRequest(imageFile.url));
    // when load of the selected image is complete we save a
    smaller version of it.
    public function handleImageComplete(event:Event):void
    var loader:Loader = Loader(event.target.loader);
    // width and heigt of selected image
    var originalimgwidth:Number=event.target.width;
    var originalimgheight:Number=event.target.height;
    //put original image into bitmapdata
    var bitmapje:BitmapData;
    bitmapje=new BitmapData(originalimgwidth, originalimgheight,
    true, 0x00000000);
    //bitmapje.draw(loaderInfo.loader.content,null,null,null,null,true);//null
    object reference
    bitmapje.draw(loader.content,null,null,null,null,true);
    // call the resize function and give the original
    image,maxx,and maxy with it.
    var thumb:BitmapData=resizeimage(bitmapje,150,150);
    var newimagefile:File=new File();
    // T = Thumbnail
    // 1 = next id in the db
    // for now we use a random number
    var random:Number= Math.random();
    random = Math.ceil(random*100);// to get a positive number
    var filenameForSave:String="T"+random; //new filename;
    newimagefile=docsDir.resolvePath("Thumbs/" + filenameForSave
    + ".png"); //image path
    var stream:FileStream = new FileStream; // create new
    filestream
    stream.open(newimagefile, FileMode.WRITE); // open
    filestream
    var data:ByteArray = encodeToPng(thumb); // convert
    bitmapdata to a png bytearry
    stream.writeBytes(data, 0, data.length); // writing the
    image
    stream.close();
    // show the saved thumb
    savedthumb.source=newimagefile.nativePath;
    bitmapje=null;
    thumb=null;
    // resize function
    private function
    resizeimage(image:BitmapData,maxx:Number,maxy:Number):BitmapData
    var bmp:BitmapData =image;
    var true_width:Number = bmp.width;
    var true_height:Number = bmp.height;
    var resize:Boolean=false;
    if (true_width>maxx) resize=true;
    if (true_height>maxy) resize=true;
    if (resize==true)
    var width:Number=maxx;
    var height:Number = (width / true_width) * true_height;
    true_width=width;
    true_height=height;
    if (true_height>maxy)
    height=maxy;
    width = (height/true_height)*true_width;
    else
    width=true_width;
    height=true_height;
    else
    width=true_width;
    height=true_height;
    //new calculated width and heigt relative to the given maxx
    and maxy.
    width=Math.ceil(width);
    height=Math.ceil(height);
    //create a new image object with the calculated widht and
    height for the smaller image
    var mysmallimage:Image=new Image();
    mysmallimage.width=width;
    mysmallimage.height=height;
    //new matrix for smaller image
    var m : Matrix = new Matrix() ;
    //scale the matrix to the correct sizes.
    m.scale( mysmallimage.width / bmp.width, mysmallimage.height
    / bmp.height ) ;
    //draw the image into the image object
    mysmallimage.graphics.beginBitmapFill( bmp, m, false, true )
    mysmallimage.graphics.drawRect( 0, 0, mysmallimage.width,
    mysmallimage.height ) ;
    mysmallimage.graphics.endFill();
    //put the smaller image into bitmapdata so it can be
    returned.
    var littlebitmapdata:BitmapData=new
    BitmapData(mysmallimage.width,mysmallimage.height,true,0x00000000);
    littlebitmapdata.draw(mysmallimage);
    // set the temporary small image to null so the GC can
    remove it from the memmory.
    mysmallimage=null;
    bmp=null;
    //returning the small image.
    return littlebitmapdata;
    // encoder to png
    private function encodeToPng(bmd:BitmapData):ByteArray
    var png:PNGEncoder= new PNGEncoder();
    return png.encode(bmd);
    ]]>
    </mx:Script>
    <!--<mx:Image id="tempimage" x="404" y="36"
    complete="temploadcomplete()"/>-->
    <mx:Image id="myimg" x="10" y="55" width="314"
    height="227" verticalAlign="middle" horizontalAlign="center"/>
    <mx:TextInput id="imageurl" x="53" y="303" width="160"
    maxWidth="160"/>
    <mx:Button x="221" y="303" label="Bladeren"
    click="imageFileDialog(myimg,imageurl)"/>
    <mx:Image x="346" y="55" id="savedthumb"/>
    <mx:Text x="23" y="0" text="Original image with limit
    width and height to show it on the screen." height="47"
    width="177"/>
    <mx:Text x="346" y="0" text="Local stored thumbnail"/>
    </mx:WindowedApplication>
    To bad the attach code button still isn't fixed :(

    Hi there,
    Will you be able to provide the backend script for saving the
    file data?Will you be able to provide the backend script for saving
    the file data?
    This example is created for a desktop application. Saving the
    file is included in this example, it saves in the application
    storage directory.
    // File.applicationStorageDirectory gets you to the local
    storage dir
    //On Windows, this is the "projectname" directory
    //(for example, C:\Documents and Settings\application
    data\projectname).
    // On Mac OS, it is /Users/userName/Documents.
    If you attempt to use certain functionality in a website, you
    need other functionality for storing the image on the server. There
    are lots of examples on that one.. Perhaps i need it in the future.
    If i do i will post an example on the forum.
    Also, may I post your link to other forums, so that others may
    benefit?
    Sure you may post the example on other websites and forums.
    I found it difficult to find nice examples, so the more the
    better ;)
    Just put underneath the example something like:
    Created By: Jacob Hingst From Holland
    No copyright attached, so free for your use.

  • How to insert image into table and to in Oracle 9i intermedia?

    Mr Lawrence,
    I want to ask something:
    I use Oracle 9i intermedia
    If i use this script:
    CREATE TABLE images (
    file_name VARCHAR2(100) NOT NULL,
    image ORDSYS.OrdImage
    then
    CREATE OR REPLACE DIRECTORY imgdir AS 'd:/data';
    then
    INSERT INTO images (file_name, image)
    VALUES ('tree', ORDSYS.ORDImage.init('file','imgdir','tree.jpg' ));
    I put tree.jpg in directory d:/data in my hard drive.
    Is my tree.jpg file had already get in to my images table?
    I'm little confuse, because when i check my table with this script:
    select file_name, i.image.getWidth() from images i;
    it's show that my i.image.getWidth() for file_name tree is empty.. that mean my tree.jpg doesn't get in to my table.. am i correct?
    N also i want to ask how to display to screen all of my image from images table?
    Is it posible Oracle 9i intermedia to support display image from table?
    How?
    thanks Mr Lawrence

    -- First step would be to create a directory in oracle and map it to the folder where your image resides.
    create directory image_dir as *'c:\image_dir';*
    Then you would have to use a procedure to insert the image in your table. SO first create a table to hold the image. Note that you have to use a BLOB to insert the image.
    CREATE TABLE test_image
    ID NUMBER,
    image_filename VARCHAR2(50),
    image BLOB
    Now let's write the procedure to insert the image in the table above.
    CREATE OR REPLACE PROCEDURE insert_image_file (p_id NUMBER, p_image_name IN VARCHAR2)
    IS
    src_file BFILE;
    dst_file BLOB;
    lgh_file BINARY_INTEGER;
    BEGIN
    src_file := BFILENAME ('image_DIR', p_image_name);
    -- insert a NULL record to lock
    INSERT INTO temp_image
    (ID, image_name, image
    VALUES (p_id, p_image_name, EMPTY_BLOB ()
    RETURNING image
    INTO dst_file;
    -- lock record
    SELECT image
    INTO dst_file
    FROM temp_image
    WHERE ID = p_id AND image_name = p_image_name
    FOR UPDATE;
    -- open the file
    DBMS_LOB.fileopen (src_file, DBMS_LOB.file_readonly);
    -- determine length
    lgh_file := DBMS_LOB.getlength (src_file);
    -- read the file
    DBMS_LOB.loadfromfile (dst_file, src_file, lgh_file);
    -- update the blob field
    UPDATE temp_image
    SET image = dst_file
    WHERE ID = p_id AND image_name = p_image_name;
    -- close file
    DBMS_LOB.fileclose (src_file);
    END insert_image_file;
    Now execute the procedure to insert the image.
    EXECUTE insert_image_file(1,'test_image.jpg');
    Thanks,
    Aparna

Maybe you are looking for