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

Similar Messages

  • Send image with MFMailComposeVewController and thread issue

    Hi,
    In my app, if user click a button, the app will generate an image and show up a MFMailComposeViewController with the image as attachment. Since it takes quite some time to generate the image, I fired up a thread and generate the image in this new thread. I am not sure what to do the next. When the image is generated, how can I tell the mail thread to launch the MFMailComposeViewController?
    Thanks,
    ff

    Have you looked at this sample yet (link)?

  • Re: Java Images and Threads prob Help!!

    Without going through it in detail the problem may be that you're doing the repaint which you hope will draw the image before the image has completed loading.
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program initialisation. And check the load status of the icon, at least in a test version.

    I still cant get the reqd output. Only the 1st image is dispayed and when i click the second code, the 2nd image doesnt come(the first one does not disappear, and even when i click the code 1 i have to minimize/ maximize the screen, to get the image and after that it does not go for the s2nd image 2 come!! )
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program >>initialisation. And check the load status of the icon, at least in a test version. How do u load the image during initialization??? and can ny1 plz tell me how to get the flashing threads with msgs????

  • Reading image stream with multiple threads

    Hello folks
    I thought about a model for an app I need to code and I need your opinion.
    My task is to implement an application that does the following:
    - Read and decode images from a stream.
    - Do some image processing
    - Display the resulting images in Swing window.
    Since decoding is expensive and i might want to use a multiprocessor machine,
    I decided to put the image reading and decoding in a different thread. from the
    image processing (and maybe painting).
    In the end, I thought about using 2 objects and 3 threads:
    - one object that keeps the Swing window data and the image processing logic
    - one object that keeps the stream connection data and the decompression logic
    for the (jpeg) images
    -one thread that waits for incoming events and decodes them. After decompressing
    one image, it sends an event to all objects that needs the image data, in this case
    this is the object that keeps the image processing logic. Therefore it updates an
    image reference in the image processing logics object. The image object only
    allow synchronized access by all threads.
    -another thread whose logic is inside the image processing logic object takes
    the current data from the image reference the first thread writes to via events
    and does image processing. The result is written to another image reference within
    the same object. After that, it sleeps for 10 ms or so.
    -a third thread is triggered via invokeLater by the image processing thread after
    it produced a result. It calls the repaint() method of the Swing control which draws
    the result-image to the screen.
    Do you see any mistakes or do you have better suggestions to do it?
    Please let me know!
    Thanks in advance!

    If the file is on a diskdrive, it's likely that your program will be i/o bound and threads won't help.
    Edited by: ChuckBing on Jul 2, 2008 11:32 AM

  • Create a new Buffered Image using Raster and ColorModel

    Sorry , I crosspost this message,because no one reply.
    Recently,I write a programme combining C++ and Java .
    The C++ part create a array containing image data in form of BI_RGB and biBitCount==32.
    The java part create a image using Raster and ColorModel like this:
       static int[] data ;
       DataBuffer db = new DataBufferInt(data, data.length);
       WritableRaster wr =Raster.createPackedRaster(db, 1024,768, 32, null);
       ColorModel cm = new DirectColorModel(32,0xff0000,0x00ff00,0x0000ff);
       img = new BufferedImage(cm, wr, false, null);But it doesn't work .
    it report this:
    Exception in thread "main" java.lang.IllegalArgumentException: Raster sun.awt.im
    age.SunWritableRaster@dff3a2 is incompatible with ColorModel DirectColorModel: r
    mask=ff0000 gmask=ff00 bmask=ff amask=0
    at java.awt.image.BufferedImage.<init>(BufferedImage.java:549)
    at monitor.test.Perform2.main(Perform2.java:39)

    hey epico
    compiles & runs 4 me
    see javadocs for SinglePixelPackedSampleModel
    import java.awt.image.*;
    public class Tester {
    DataBuffer db;
    WritableRaster wr;
    ColorModel cm;
    BufferedImage im;
    int[] data;
    int[] masks;
    int w = 768;
    int h = 576;
      public Tester() {
        data = new int[768*576];
        for (int i = 0;i < w*h ;i++ ) {
          data[i] = 0;
        masks = new int[3];
        masks[0] = 0xff0000;
        masks[1] = 0x00ff00;
        masks[2] = 0x0000ff;
        db = new DataBufferInt(data,data.length);
        SinglePixelPackedSampleModel sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT,w,h,masks);
        cm = new DirectColorModel(32,0xff0000,0x00ff00,0x0000ff);
        wr = Raster.createWritableRaster(sm,db,null);
        im = new BufferedImage(cm,wr,false,null);
      public static void main(String[] args) {
        Tester tester1 = new Tester();
    }

  • My 4s has grainy low res images when I use google image search, imdb and USA today app. But not FB. How do I fix this?

    My 4s images are grainy and low res when I use google image search, imdb and a couple other apps. My photos roll pics are hi def just not images. What's up with this?

    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    Additional things to try.
    Try this first. Turn Off your iPad. Then turn Off (disconnect power cord for 30 seconds or longer) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    Change the channel on your wireless router (Auto is best). Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    Another thing to try - Go into your router security settings and change from WEP to WPA with AES.
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    If none of the above suggestions work, look at this link.
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    Fix Slow WiFi Issue https://discussions.apple.com/thread/2398063?start=60&tstart=0
    Unable to Connect After iOS Update - saw this solution on another post.
    https://discussions.apple.com/thread/4010130
    Note - When troubleshooting wifi connection problems, don't hold your iPad by hand. There have been a few reports that holding the iPad by hand, seems to attenuate the wifi signal.
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • Repaint() is not thread-safe?

    I saw a description that says repaint() is thread-safe in an old swing tutorial, but not in the current tutorial and its javadoc. So can I assume repaint() is not thread-safe and I should call it from EDT? ... Or if they are thread-safe, why does Sun not document it?

    repaint() calls paint() on EDT... but it calculates dirty region on the current thread and does not get AWTTreeLock.I don't think so.
    repaint() is a java.awt.Component method and doesn't know about Swing's RepaintManager and dirty regions. There may be somthing similar at the AWT level that escaped me, but looking at the JDK1.6 source code, java.awt.Component.repaint() just repaints the whole component.
    Now repaint(long, int, int, int, int) has two versions.
    At the AWT level, it just posts a paint event for the specified region. No race condition, and no risk that he region be wrong, but possibility to invoke multiple paint(Graphics) that overlap, that is, to paint several times the same area - it may be an optimization problem, but it doesn't jeopardize the consistency of the drawing.
    At the Swing level, it does compute dirty regions. In Repaint manageer, the call to extendDirtyRegion(...) is protected within a synchronized block, but the code before that is not. From a quick look, that code is:
    1) walking up the component hierarchy to find the root, which may not be thread-safe, but a well-behaved application shouldn't change the hierarchy from outside the EDT.
    2) walking up a chain of "delegate" RepaintManager, which I knew nothing about... Apparently it's a sun's implementation specific construct, each JComponent can be assigne d a delegate RepaintManager. Again I would claim that such things should not happen outside of the EDT, but I haven't found documentation about this.
    Edited by: jduprez on Jul 20, 2009 2:37 PM
    so no, technically, I can't prove repaint(long, int,int,int,int) is thread-safe.
    But a well-behaved application that updates its widgets on the EDT shouldn't worry (that is, repaint(...) calls can still be invoked outside of the EDT).
    Edited by: jduprez on Jul 21, 2009 7:04 PM - typos

  • Example of WAIT and CONTINUE using checkBox and thread and getTreeLock()

    I had so much trouble with this that I descided to
    post if incase it helps someone else
    // Swing Applet example of WAIT and CONTINUE using checkBox and thread and getTreeLock()
    // Runs form dos window
    // When START button is pressed program increments x and displys it as a JLabel
    // When checkBox WAIT is ticked program waits.
    // When checkBox WAIT is unticked program continues.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    public class Wc extends JApplet {
    Display canvas;//drawing surface is displayed.
    Box buttonPanel;
    Box msgArea;
    public static JButton button[] = new JButton [2];
    public static JCheckBox checkBox[] = new JCheckBox[2];
    public static JLabel msg[] = new JLabel [2];
    String[] buttonDesc ={"Start","Quit"};
    public static final int buttonStart = 0;
    public static final int buttonQuit = 1;
    String[] checkBoxDesc ={"Wait"};     
    public static final int checkBoxWait = 0;
    public boolean wait;
    public Graphics g;
    //================================================================
    public static void main(String[] args){
    Frame f = new Frame();
    JApplet a = new Wc();
    f.add(a, "Center"); // Add applet to window
    a.init(); // Initialize the applet
    f.setSize(300,100); // Set the size of the window
    f.show(); // Make the window visible
    f.addWindowListener(
    new WindowAdapter(){
    public void windowClosing(WindowEvent e){System.exit(0);}
    }// end main
    //===================================================
    public void init() {
    canvas = new Display();
    setBackground(Color.black);
    getContentPane().setLayout(new BorderLayout(3,3));
    getContentPane().add(canvas, BorderLayout.CENTER);
    buttonPanel = Box.createHorizontalBox();
    getContentPane().add(buttonPanel, BorderLayout.NORTH);
    int sbZ;
    // add button
    button[0] = new JButton(buttonDesc[0]);
    button[0].addActionListener(canvas);
    buttonPanel.add(button[0]);
    button[1] = new JButton(buttonDesc[1]);
    button[1].addActionListener(canvas);
    buttonPanel.add(button[1]);
    // add checkBox
    sbZ=0;
    checkBox[sbZ]=new JCheckBox(checkBoxDesc[sbZ]);
    checkBox[sbZ].setBackground(Color.white);
    checkBox[sbZ].setOpaque(true);
    checkBox[sbZ].addActionListener(canvas);
    buttonPanel.add(checkBox[sbZ]);
    msgArea = Box.createVerticalBox(); // add message
    sbZ=0;
    msg[sbZ]=new JLabel("1",JLabel.LEFT);
    msg[sbZ].setOpaque(true);
    msg[sbZ].setBackground(Color.black);
    msg[sbZ].setForeground(Color.red);
    msgArea.add(msg[sbZ]);
    getContentPane().add(msgArea, BorderLayout.SOUTH);
    } // end init();
    //===================================================
    public void stop(){canvas.stopRunning();}
    //===================================================
    // The following nested class represents the drawing surface
    // of the applet and also does all the work.
    class Display extends JPanel implements ActionListener, Runnable {
    Image OSI;
    Graphics OSG; // A graphics context for drawing on OSI.
    Thread runner; // A thread to do the computation.
    boolean running; // Set to true when the thread is running.
    public void paintComponent(Graphics g) {
    if (OSI == null) {
    g.setColor(Color.black);
    g.fillRect(0,0,getWidth(),getHeight());
    else {g.drawImage(OSI,0,0,null);}
    }//paintComponent
    public void actionPerformed(ActionEvent evt) {
    String command = evt.getActionCommand();
    if (command.equals(buttonDesc[buttonStart])) {
    startRunning();
    if (command.equals(buttonDesc[buttonQuit])) {
    stopRunning();
    if (command.equals(checkBoxDesc[checkBoxWait])){
    System.out.println("cb");
    if (checkBox[checkBoxWait].isSelected() ) {
    wait = true;
    System.out.println("cb selected twait "+wait);
    return;
    wait = false;
    synchronized(getTreeLock()) {getTreeLock().notifyAll();}
    System.out.println("cb selected fwait "+wait);
    } // end command.equal cb wait
    } //end action performed
    // A method that starts the thread unless it is already running.
    void startRunning() {
    if (running)return;
    // Create a thread that will execute run() in this Display class.
    runner = new Thread(this);
    running = true;
    runner.start();
    } //end startRunning
    void stopRunning() {running = false;System.exit(0);}
    public void run() {
    button[buttonStart].setEnabled(false);
    int x;
    x=1;
    while(x>0 && running){
    x = x + 1;
    msg[0].setText(""+x);
    try{SwingUtilities.invokeAndWait(painter);}catch(Exception e){}
    //importand dont put this in actionPerformed
    if (wait) {
    System.out.println("run "+wait);
    synchronized(getTreeLock()) {
    while(wait) {
    System.out.println("while "+wait);
    try {getTreeLock().wait();} catch(Exception e){break;}
    } //end while(wait)
    } // end sync
    } // end if(wait)
    } // endwhile(x>0)
    stopRunning();
    } // end run()
    Runnable painter = new Runnable() {
    public void run() {
    Dimension dim = msg[0].getSize();
    msg[0].paintImmediately(0,0,dim.width,dim.height);
    Thread.yield();
    }//end run in painter
    } ; //end painter
    } //end nested class Display
    } //end class Wc

    I just encountered a similar issue.  I bought a new iPhone5s and sent my iPhone4s for recycling as it was in great shape, no scratches, no breaks, perfect condition.  I expected $200 and received an email that I would only receive $24.12.  The explanation was as follows:  Phone does not power on - Power Supply Error.   Attempts to discuss don't seem to get past a customer service rep that can only "escalate" my concern.  They said I would receive a response, but by email.  After 4 days no response.  There is something seriously wrong with the technical ability of those in the recycling center.

  • Image.getWidth(null) and image..getHeight(null)  returns -1

    Hi ,
    Plz tell me whats wrong with code
    import java.awt.Image;
    import java.awt.Toolkit;
    public class ImgSize {
        public static void main(String args[]) {
            Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
            getImageDimesion("Picture.jpg");
        public static void getImageDimesion(String abc) {
            Image image = Toolkit.getDefaultToolkit().getImage(abc);
            double width = image.getWidth(null);
            double height = image.getHeight(null);
            System.out.println("width :" + width + "-- height :" + height);
    }output:
    width :-1.0-- height :-1.0
    width :2592.0-- height :1944.0
    There is no difference in main function getWidth/ getHeight and function getImageDimension getWidth/ getHeight
    If u remove getWidth and getHeigth in the main function i.e comment the 1st four lines in main function then the output is
    Output
    width :-1.0-- height :-1.0
    Plz help in understanding this.
    Thanks
    Venkat

    Toolkit images are not loaded until they are first drawn or you request a property from it (such as getWidth). To force the image to load and wait for it to finish loading, you can use the MediaTracker class. The ImageIcon class has one built in.
    Image image = Toolkit.getDefaultToolkit().getImage("Picture.jpg");
    new ImageIcon(image); //loads the image

  • 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.

  • Convert a Tiff Image to png and show

    Hello;
    I wanto to convert a Tif image to png and show this in my web page but i dont want to save the png iamge in my server.
    Actualy i do that:
    byte[] bytes = imagenData;
                    ByteArraySeekableStream tiffStrm = new ByteArraySeekableStream(bytes);
                    String[] CdcNms = ImageCodec.getDecoderNames(tiffStrm);
                    ImageDecoder tifDecoder = ImageCodec.createImageDecoder(CdcNms[0], tiffStrm, new TIFFDecodeParam());
    //                 Check the number of pages
                    int IFDs = tifDecoder.getNumPages();
    //                 Get the first page
                    RenderedImage ren = tifDecoder.decodeAsRenderedImage(1);
                    byte[] bytes2 = doSingleConversion(ren);AND
    protected byte[] doSingleConversion(RenderedImage tifImage) throws Exception
              byte[] bytes = null;
              String out = "temp.png";
              try {
                   //      Create the PNG file
                   PNGEncodeParam pngParm = PNGEncodeParam.getDefaultEncodeParam(tifImage);
                   JAI.create("filestore", tifImage, out, "PNG", pngParm);
                   //Read the file into a byte array
                   File f = new File(out);
                   FileInputStream in = new FileInputStream(f);
                   bytes = new byte[(int) f.length()];
                   in.read(bytes);
                   in.close();
                   return bytes;
              catch(Exception e) {
                   e.printStackTrace ();
                   throw(e);
         }But this code save de image in the server; it�s posible do it without save.

    Numbers the iWorks program? Not sure you can convert it to that or just a list of numbers. Never heard of anyone that would even want to convert an Image file, Photo, to any other format. Other then another image format like JPG, PNG or a PSD Photoshop file.

  • 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.

  • Silicon image sil 3112 and seagate 200GB sata

    hey everyone..
    im trying hard to get dma activated on my sata drive..i dont need raid(and cant have it..only one sata drive  ...but hdparm -tT shows slower performance on the sata drive
    /dev/sda = sata
    /dev/hda = pata
    /dev/sda
    hdparm -Tt /dev/sda
    /dev/sda:
    Timing cached reads:   1008 MB in  2.01 seconds = 502.32 MB/sec
    HDIO_DRIVE_CMD(null) (wait for flush complete) failed: Inappropriate ioctl for device
    Timing buffered disk reads:   58 MB in  3.05 seconds =  19.04 MB/sec
    HDIO_DRIVE_CMD(null) (wait for flush complete) failed: Inappropriate ioctl for device
    hdparm /dev/sda
    /dev/sda:
    IO_support   =  0 (default 16-bit)
    readonly     =  0 (off)
    readahead    = 256 (on)
    geometry     = 24321/255/63, sectors = 390721968, start = 0
    hdparm -i /dev/sda
    /dev/sda:
    HDIO_GET_IDENTITY failed: Inappropriate ioctl for device
    the results for the pata drive are
    /dev/hda
    hdparm -Tt /dev/hda
    /dev/hda:
    Timing cached reads:   996 MB in  2.00 seconds = 497.58 MB/sec
    Timing buffered disk reads:  120 MB in  3.00 seconds =  39.97 MB/sec
    im able to enable dma/set Xfer mode/IO/ only in the pata drive, not in the sata drive..in kernel config ive enabled "scsi low-level->sata support->silicon image sata support" and also enabled "silicon image chipset support under ATA/ATAPI/MFM/RLL support"
    im right now using sata as root and the drive is stable..just need dma..thanks in advance

    According to Jeff Garzik's sata pages the drivers for the Sil 311x chipsets have beta status.
    I had worse luck with my no-name PCI Sil-SATA controllers: as soon as I connected a hard disk the kernel would not boot anymore when using libata drivers. I can only use the allegedly deprecated IDE drivers,  these work fine for me.
    The libata drivers should set the proper DMA modes automatically, but things are slightly different with SATA. Anyways, 20MB/s is proof enough that some sort of DMA is actually there. Performance would be much worse without any DMA at all.
    If you really want to use the libata driver you should try a 2.6.12rc kernel, libata has seen quite a many updates since 2.6.11
    Cheers,
    Dominik

  • Why do I get Colored bands on some images in LR4 and LR5, but not in Aperture?

    On some images -- both RAW and JPG -- when opened in LR4 or LR5, there will be one or two "curved" color abberation lines across the entire image. This doesn't occur when I open the images in Aperture. Any idea why? Thanks

    >Is it possible that Aperture is showing you the camera-embedded JPG by default?  What happens if you actually produce a JPG from the raw file in Aperture?
    Aperture works the same way as Lightroom in this respect. It will first show you the embedded jpeg and will render a new conversion from the raw data as soon as it can. So it is possible the OP saw the embedded jpeg, but that should not last long and certainly by now should have been replaced with a newly rendered preview. Either Aperture is more forgiving of a small defect in the raw file or Lightroom import is somehow getting corrupt files of the sd card and Aperture not (would be weird). Another option is that the camera raw cache is corrupt. This can be checked by emptying the cache (Preferences->File Handling->Purge Cache). Lastly, this might be a corrupt preview in Lightroom. Check this by zooming 1:1 on an offending area in the Develop module and seeing if it goes away.
    >I suspect that the curvature is in fact due to lens corrections, and that these lens corrections are always on
    I believe you are right. I remember vaguely that there is some default lens correction with some cameras like this that is independent of the lens correction module. No clue whether the LX7 is one.

  • Problem in creating client side PDF with image using flex and AlivePD

    I need a favor I am creating client side PDF with image using flex and AlivePDF for a web based application. Images have been generated on that pdf but it is creating problem for large size images as half of the image disappeared from that pdf.I am taking the image inside a canvas . How do i control my images so that they come fit on that pdf file for any image size that i take.
    Thanks in advance
    Atishay

    I am having a similar and more serious problem. It takes a
    long time to execute, but even attaching a small image balloons the
    pdf to 6MB plus. After a few images it gets up to 20MB. These are
    100k jpeg files being attached. The resulting PDF is too large to
    email or process effectively. Does anyone know how to reduce
    size/processing?

Maybe you are looking for

  • My earlier made PDF acrobat XI pro file won't open edit form

    I made a form and want to chance the fields, but now it gives an error?? 

  • Data missing when Exporting or print preview from ALV report

    Hi I have a alv report which is showing fine but when i try to export it to say excel sheet or do print preview some of the data is missing. Can anyone tell me how to fix this. or at least point to some document that discuss this problem. Here is my

  • Path Selection Tool issues

    After reading up on some of the problems people are having with the path/shape changes in CC 2014, I haven't seen an exact mention of the problem I am having so here I am. 2 part problem really: 1. When using the Path Selection Tool or Direct Selecti

  • LDAP Error 50 configuring OC4J in 9ias Rel 2

    Hello everybody, I'm trying to install 9ias Rel 2 on a Windows 200 Server machine. Unfortunatly after 3 tries i'm continuing receiving the following error during the OC4J configuration step in a Business Intelligence Installation type ( i want to say

  • Authorization objects to function module

    Hi Experts           I want to set the authorization object to the particulare function module.           How can we set the authorization objects to the function modules, plese explain me briefly. regards rajaram