BufferedImage performance

Hi All,
I have a thread that serves me a java.awt.Image. Many of these Images come through per second. Each time an Image comes through I create a new BufferedImage and call the paintComponent method on my JPanel to display the BufferedImage. The problem is that it is really slow. Does anyone have some performance tips for me that would make the generation of the BufferedImage quicker?
Example Code:
public void displayImage(Image image){
BufferedImage buff = new BufferedImage(image.getWidth(this), image.getHeight(this), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = buff.createGraphics();
g2d.drawImage(image,0,0,this);
paintPanel(buff);
The method paintPanel(BufferedImage) overrides paintComponent and draws the image to the JPanel.
Any help would be greatly appreciated.

If you already have an Image, why do you need to make it a BufferedImage?

Similar Messages

  • Performance of BufferedImage.getRGB(int x, int y)

    Hi,
    My app uses the getRGB method call to extract the RGB values for each pixel contained within an image. This works fine on some images, from the beginning to the end of the process of loading, reading values, and then displaying only taking 2 or 3 seconds.
    But this method does have issues with certain images where it can take upto 15 seconds. I'm not certain what causes this because it's not down to the file size or image size itself, as i get an 1556 * 1054 jpeg file (303KB) to open in about 2 seconds where as a certain 800 * 600 jpeg file (152KB) takes upto 15 seconds.
    Does anyone have any idea what is causing this slowdown because I can only think that it might be something to do with the compression used but that is only a guess.
    Can anyone help ?

    I am loading the image in via the ImageIO.read so the image is already in a BufferedImage format, so to read it into a seperate byte array for each colour channel would require me to write my own load methods for all of the supported image types, i don't want to do this.

  • Image Processing Performance Issue | JAI

    I am processing TIFF images to generate several JPG files out of it after applying image processing on it.
    Following are the transformations applied:
    1. Read TIFF image from disk. The tiff is available in form of a PlanarImage object
    2. Scaling
         /* Following is the code snippet */
         PlanarImage origImg;
         ParameterBlock pb = new ParameterBlock();
         pb.addSource(origImg);
         pb.add(scaleX);
         pb.add(scaleY);
         pb.add(0.0f);
         pb.add(0.0f);
         pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
         PlanarImage scaledImage = JAI.create("scale", pb);3. Convertion of planar image to buffered image. This operation is done because we need a buffered image.
         /* Following is the code snippet used */
         bufferedImage = planarImage.getAsBufferedImage();4. Cropping
         /* Following is the code snippet used */
         bufferedImage = bufferedImage.getSubimage(artcleX, artcleY, 302, 70);The performance bottle neck in the above algorithm is step 3 where we convert the planar image to buffered image before carrying out cropping.
    The operation typically takes about 1120ms to complete and considering the data set I am dealing with this is a very expensive operation. Is there an
    alternate to the above mentioned approach?
    I presume if I can carry out the operation mentioned under step 4 above on a planr image object instead of buffered image, I will be able to save
    considerable processing time as in this case step 3 won't be required. (and that seems like the bottle neck). I have also noticed that the processing
    time of the operation mentioned in step 3 above is proportional to the size of the planar image object.
    Any pointers around this would be appreciated.
    Thanks,
    Anurag
    Edited by: anurag.kapur on Oct 4, 2007 10:17 PM
    Edited by: anurag.kapur on Oct 4, 2007 10:17 PM

    It depends on whether you want to display the data or not.
    PlanarImage (the subclass of all renderedOps) has a method that returns a Graphics object you can use to draw on the image. This allows you to do this like write on an image.
    PlanarImage also has a getAsBufferedImage that will return a copy of the data in a format that can be used to write to Graphics objects. This is used for simply drawing processed images to a display.
    There is also a widget called ImageCanvas (and ScrollingImagePanel) shipped with JAI (although it is not a committed part of the API). These derive from awt.Canvas/Panel and know how to render RenderedImage instances. This may use less copying/memory then getting the data as a BufferedImage and drawing it via a Graphics Object. I can't say for sure though as I have never used them.
    Another way may be to extend JComponent (or another class) and customize it to use calls to PlanarImage/RenderedOp instances directly. This can hep with large tiled images when you only want to display a small portion.
    matfud

  • Better TIFF Performance

    Hi,
    I would like to display TIFF images in a JPanel more quickly than I do now.
    Currently, I use this JAI code :
           PlanarImage pi = JAI.create("fileload", "C:\\image.tif");
           ColorModel colmodel = pi.getColorModel();
           Rectangle rect = new Rectangle(new Dimension(pi.getWidth(), pi.getHeight()));
           BufferedImage buf = pi.getAsBufferedImage(rect, colmodel);And here I have my BufferedImage that I can display in my JPanel.
    That's works, but that also does have very bad performances : it needs a few seconds to open a simple TIFF G4 (Bilevel, B&W) image.
    Does someone know a better way to load TIFF images with JAI ?
    Thanks.
    Hugo.

    Hi,
    I don't know if this will lead to a performance boost but try this
    load method:
    public BufferedImage loadImageAsStream(File f) throws IOException {
            SeekableStream s = new FileSeekableStream(f);
            // maybe params for your tiff-file
            TIFFDecodeParam param = null;
            ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
            // Which of the multiple images in the TIFF file do we want to load
            // 0 refers to the first, 1 to the second and so on.
            int imageToLoad = 0;
            // older version
            RenderedImage op =
                    new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
                    null,
                    null,
                    OpImage.OP_IO_BOUND);
            BufferedImage buf = null;
            //System.out.println("Colormodel " + op.getColorModel().getColorSpace().getType());
            // tiff with one subimage
            if (dec.getNumPages() == 1) {
                buf = PlanarImage.wrapRenderedImage(dec.decodeAsRenderedImage()).getAsBufferedImage();
            else{
                // do load all pictures of a tiff ...
            return buf;
        }Olek

  • Monitoring progress when performing filter operations on images

    Hi,
    I am working on Java2D and making some image filters using classes like ImageFilter etc. Now For simple filters I want to get the progress status while the filteting is in progress, so that I can show a progress bar in the GUI.
    For this I do not have much idea. I think we can use the ImageConsumer interface, so that if the class implementing that interface list itself as an image consumer with the filter operation. Here is two way I have tried implanting this:
    1st way:
    Class MyConsumer implements ImageConsumer
    int width,height;
    int percentProgress;
    Public image processImage(Image srcImage, ImageFilter filter){
    FilteredImageSource fis: new FilteredImageSource(srcImage.getSource(),filter());
    //should we do this?
    fis.addConsumer(this);
    //or this?
    srcimage.addConsumer(this)
    Image destImage = this.createImage(fis);
    return destImage;
    //implementing methods of imageConsumer
    //we get the width and height of the new destImage (or do we get the dimension of the srcImage here??)
    public void setDimensions(int width, int height){
    this.width=width;
    this.height=height;
    public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize){
    // Is this the correct way of obtaining the progress????
    progressPercent=(y*100)/height;
    //We also have empty implementation of other ImageConsumer methods after this
    --------------------------------------------------------------2nd way, let?s say we use a smooth filter and replace the processImage(..) method above with the one below (the other methods being same):
    Public image processImage(Image srcImage){
    float[] SHARPEN3x3 = {      0.f, -1.f, 0.f,
                                -1.f, 5.0f, -1.f,
                                0.f, -1.f, 0.f};
    BufferedImage dstbimg = new
                  BufferedImage(iw,ih,BufferedImage.TYPE_INT_RGB);
    Kernel kernel = new Kernel(3,3,SHARPEN3x3);
    ConvolveOp cop = new ConvolveOp(kernel,
                                    ConvolveOp.EDGE_NO_OP,
                                    null);
    //should we do this?
    dst.addConsumer(this);
    //or this?
    srcImage.addConsumer(this);
    cop.filter(srcImage,destImage);
    return destImage;
    }Now I do get a progressPercent. But when the percent is 100%, the destimage does not return, that means the operation is not yet complete.
    So is this the correctw ay, or is there any other way to know the progress of the flter operation.
    Also I extended the ImageFilter class and overrode its setPixel method as:
    public void setPixels(int x, int y, int w, int h, ColorModel model, int[] pixels, int off, int scansize){
    int progressPercent=(y*100)/height;
    System.out.println("progress in image filter:"+progressPercent);
    //I simply print out the progress and let the super perform the filter operation
    super.setPixels(x, y,w, h, model, pixels, off, scansize);
    //should I do this below? This calls the imageconsumer's setpixels
    //that I implement in the MyConsumer class
    consumer. setPixels(x, y,w, h, model, pixels, off, scansize);
    }I observe that the setPixel method of MyImageFilter is called several times even for the same scan lines, and even after percentProgress is 100%, the process runs again for 2-4 times. So the filtering operation scans the lines several times to finally perform the filtering, and as such the percentProgress is incorrect.
    Can anybody guide me. Is this approach okay and needs to be modified a bit, or there is a different approach to obtain the progress from a filter operation?
    I would finally want the same progress from other operations like LookupOp, ConvolveOp, AffineTransformOp, ColorConvertOp, RescaleOp.
    Thanks in advance
    Tanveer
    DrLaszloJamf, are you there? I am sure you are one of them who can help me in this.
    anyone can send me a private message too at [email protected]

    Please somebody let me know how to get the progress of imagefilter operation using convolveOp.filter(...) or Filteredimagesource. I waant to display the progress i a JProgressbar.

  • Plz Help me in Image & BufferedImage conversion

    Hello Every One,
    I want to convert a Image object to one of its subclass BufferImage
    Direct conversion is not allowed.
    Image i;//
    BufferedImage bi;
    bi = (BufferedImage)i;
    This is run time exception.
    Please Tell me how can i perform this conversion.
    Thanx in Advance.

    As this FS seems to be for lingerie company "Victoria's Secret" could points be converted to underwear instead of t-shirts?
    Tip: If you're going to post an entire spec you may want to remove the customer's name first.

  • BufferedImage memory issue.

    Hi! I'm writing an application that is basically an image filter:
    It takes a low-resolution input image and converts the grayscale value of each pixel into a font size. The font size is then used to render characters from a text file onto corresponding coordinates in a high-resolution output image, thus creating an image from words. (I call it "one image is thousand words"*. Poetic, isn't it?)
    The application performs well for moderate size output images (say 2500x2500 pixels) but since the goal is to print these images at high quality in large formats I need to achieve resolutions of roughly 7200 pixels square, which throws the OutOfMemory error when initializing the output image's BufferedImage. This happens also if I set the heap space to its maximum allowed value.
    How do I work around this problem?
    I use the BufferedImage class for all image data handling.
    Cheers/ Jomik
    *Allthough theoretically, the application can handle far more than thousand words :)
    Edited by: jomik on Apr 15, 2008 6:56 AM
    Edited by: jomik on Apr 15, 2008 6:58 AM

    I suggest working with at most a single instance of BufferedImage at any one time. Since you say the error is thrown when you initialize your output image do you still have other instances like input around?
    To help mitigate the problem also consider forcing the garbage collector to free memory right before you initialize the image, Runtime.getRuntime().gc();
    -CollegeJavaStudent

  • BufferedImages and Swing's ScrollablePicture in a JPanel

    I'm referring to http://java.sun.com/developer/technicalArticles/Media/imagestrategies/index.html paper.
    As I read this excellent paper, I decided to go for the BufferedImage strategy.
    But I can't put my BufferedImage into my ScrollablePicture as below:
    JPanel picPanel = new JPanel(new GridBagLayout());
    //Set up the scroll pane.
    picture = new ScrollablePicture(imageIcon_, columnView.getIncrement()); // OK
    //picture = new ScrollablePicture(bImg, columnView.getIncrement()); // NOT OK = don't work
    ...How to bypass the message "java:542: cannot resolve symbol symbol : constructor ScrollablePicture (java.awt.image.BufferedImage,int)"
    It is very important as all my code is based on BufferedImage to apply many operations on the image.
    ? I believe the API does not allow to perform RGB to B&W operation on ImageIcon. ?
    Thanks to all.
    dimitryous r.

    Hi camickr,
    Hi all,
    I pass trough my SSCCE. Good advice from camickr. But it was not so easy:
    Short: not so short
    Self contained: believe so
    Correct: Java 1.4.2 code
    Compilable: yes
    I'm back with formatted code.
    I'm sure you will fire at me all of you. Anyway if I don't even try, I will never succeed.
    //  TooAwoo.java
    //  TooAwoo
    //     part of this code is from Sun's JavaTutorial 1.4.2
    import java.applet.Applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.GraphicsEnvironment;
    import java.awt.image.*;
    import java.lang.*;
    import java.lang.String;
    import java.lang.Object;
    import java.net.URL;
    import java.net.MalformedURLException;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.ImageIcon;
    import javax.swing.JScrollPane;
    import javax.swing.JToggleButton;
    import java.io.FilePermission;
    public class TooAwoo extends JApplet implements
                                                                ChangeListener,
                                                                ActionListener,
                                                                ItemListener
         FilePermission p = new FilePermission("<<ALL FILES>>", "read,write");
        public BufferedImage bImg;
         Font newFont = new Font("SansSerif", Font.PLAIN, 10);
         ImageControls RightPanel;
         public static int initOx = 0;
         public static int initOy = 0;
         int init_ww, init_wh, set_x, set_y = 0;
         final int pSP_w = 520; // final width of pictureScrollPane
         final int pSP_h = 650; // final height of pictureScrollPane
         Dimension applet_window; // applet dimensions
         public Image image;
         public ImageIcon imageIcon_;
         public static BufferedImage binull;
         // ScrollablePicture stuff
         public Rule columnView;
        public Rule rowView;
         public JToggleButton isMetric;
        public ScrollablePicture picture;
         public JScrollPane pictureScrollPane;
         public TooAwoo() {
              // nothing here
        public void init() {
              applet_window = getSize();                                                            // read applet dimensions in TooAwoo.html
              init_ww = applet_window.width;
              init_wh = applet_window.height;
              // get the image to use width > 680 (see final int pSP_w above)
              image = getImage(getDocumentBase(), "images/ReallyBig.jpg");
              imageIcon_ = createImageIcon("images/ReallyBig.jpg");
              int iw = imageIcon_.getIconWidth();
              int ih = imageIcon_.getIconHeight();
              bImg = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
              // Panels
              // ImageDisplayPanel
            //Create the row and column headers.
            columnView = new Rule(Rule.HORIZONTAL, true);
            rowView = new Rule(Rule.VERTICAL, true);
            if (imageIcon_ != null) {
                columnView.setPreferredWidth(imageIcon_.getIconWidth());
                rowView.setPreferredHeight(imageIcon_.getIconHeight());
            } else {
                columnView.setPreferredWidth(640);
                rowView.setPreferredHeight(480);
            //Create the upper left corner.
            JPanel buttonCorner = new JPanel();                                                  //use FlowLayout
            isMetric = new JToggleButton("cm", true);
            isMetric.setFont(newFont);
            isMetric.setMargin(new Insets(2,2,2,2));
            isMetric.addItemListener(this);                                                       // !!! not OK = don't work: button is not firing
            buttonCorner.add(isMetric);
              JPanel ImageDisplayPanel = new JPanel(new GridBagLayout());
            //Set up the scroll pane.
              picture = new ScrollablePicture(imageIcon_, columnView.getIncrement());     // either
              //picture = new ScrollablePicture(bImp, columnView.getIncrement());          // or
              // ********** if bImp change the lines in ScrollablePicture.java **********
            Graphics g = bImg.getGraphics();
              g.drawImage(bImg, 0, 0, null);
              JScrollPane pictureScrollPane = new JScrollPane(picture);
            pictureScrollPane.setPreferredSize(new Dimension(pSP_w, pSP_h));
            pictureScrollPane.setViewportBorder(
                    BorderFactory.createLineBorder(Color.black));
            pictureScrollPane.setColumnHeaderView(columnView);
            pictureScrollPane.setRowHeaderView(rowView);
              //Set the corners.
            pictureScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, buttonCorner);
            pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER,
                                        new Corner());
            pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER,
                                        new Corner());
              //set_y++;
              addToGridBag(ImageDisplayPanel,pictureScrollPane, set_x, set_y, 1, 1, 0, 0); // 0,0
              getContentPane().add( BorderLayout.WEST, ImageDisplayPanel);               // where to display the bImg: left
              RightPanel = new ImageControls();                                                  // call the ImageControls class
              RightPanel.setBackground(Color.black);
              getContentPane().add( BorderLayout.EAST, RightPanel);
              //getContentPane().add( BorderLayout.EAST, ToolsPanel);                         // where to display the tools: right
              JPanel GlobalPanel = new JPanel(new GridBagLayout());
              getContentPane().add( BorderLayout.NORTH, GlobalPanel);
         } // end public void init()
         public Graphics2D createGraphics2D(int width,
                                                    int height,
                                                    BufferedImage bi,
                                                    Graphics g) {                                   // called by ImageControls paint
              Graphics2D g2 = null;
              if (bi != null) {
                   System.out.println("TooAwoo createGraphics2D: bi != null : " + " w= " + width + " h= " + height);
                   g2 = bi.createGraphics();
              } else {
                   System.out.println("TooAwoo createGraphics2D: bi == null g2 = (Graphics2D) g");
                   g2 = (Graphics2D) g;
              return g2; // return to ImageControls paint
         } // end createGraphics2D
         class ImageControls extends JPanel {
              public void paint(Graphics g) {
                   Dimension applet_window = getSize();
                   if (bImg == null) {
                        bImg = createBufferedImage(applet_window.width, applet_window.height, 2);
                   } else {
                        Graphics2D g2 = createGraphics2D(applet_window.width, applet_window.height, bImg, g);
                        g.drawImage( bImg , initOx , initOy , null );
                        g2.dispose();
                        //toolkit.sync();
                   } // end else (bImg != null)
              } // end paint
         } // end ImageControls
         public Dimension setPreferredSize() {
              Dimension applet_window = getSize();
              return applet_window;
         public String getString(String key) {
              return key;
         public BufferedImage createBufferedImage(int w, int h, int imgType) {          // called by ImageControls paint
              BufferedImage bi = null;
              if (imgType == 0) {
                   bi = (BufferedImage) getGraphicsConfiguration().createCompatibleImage(w, h);
              } else if (imgType > 0 && imgType < 14) {
                   bi = new BufferedImage(w, h, imgType);
              System.out.println("TooAwoo createBufferedImage: imgType= " + imgType + " w= " + w + " h= " + h);
              return bi;
         public static void addToGridBag(JPanel panel, Component comp,
                                                 int x, int y, int w, int h, double weightx, double weighty) {
              GridBagLayout gbl = (GridBagLayout) panel.getLayout();
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
              c.anchor = GridBagConstraints.WEST;
              c.gridx = x;
              c.gridy = y;
              c.gridwidth = w;
              c.gridheight = h;
              c.weightx = weightx;
              c.weighty = weighty;
              panel.add(comp);
              gbl.setConstraints(comp, c);
         } // end addToGridBag
         protected static ImageIcon createImageIcon(String path) {                         // Returns an ImageIcon, or null if the path was invalid.
              java.net.URL imgURL = TooAwoo.class.getResource(path);
              if (imgURL != null) {
                   return new ImageIcon(imgURL);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
         } // end createImageIcon
         private static void createAndShowGUI() {                                             // called by main
              JFrame frame = new JFrame("TooAwoo");                                             //Create and set up the window.
              // Make sure we have nice window decorations.
              frame.setDefaultLookAndFeelDecorated(true);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Create and set up content pane.
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              JPanel masterPanel = new JPanel();
              frame.add("Center", masterPanel);
              // Display the window.
              frame.pack();
              frame.setSize(new Dimension( 1000 , 640 ));
              frame.setVisible(true);
         } // end createAndShowGUI
         public static void main(String s[]) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
         } // end main
         public void actionPerformed(ActionEvent e) {
              repaint(1024);
        public void stateChanged(ChangeEvent e) {
              repaint(1024);
         public void itemStateChanged(ItemEvent e) {
              Object obj = e.getSource();
              if ( obj == isMetric ) {
                   System.out.println("obj isMetric");
                //Turn it to metric.
                rowView.setIsMetric(true);
                columnView.setIsMetric(true);
                   picture.setMaxUnitIncrement(rowView.getIncrement());
            } else {
                System.out.println("obj isNotMetric");
                   //Turn it to inches.
                rowView.setIsMetric(false);
                columnView.setIsMetric(false);
                   picture.setMaxUnitIncrement(rowView.getIncrement());
         } // end itemStateChanged(ItemEvent e)
    } // end TooAwoo
    Next is ScrollablePicture.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class ScrollablePicture extends JLabel implements Scrollable {
        private int maxUnitIncrement = 1;
         private boolean missingPicture = false;
        public ScrollablePicture (ImageIcon imageIcon_, int m){                              //(BufferedImage bImg, int m)
            super(imageIcon_); // comment this line if bImg...
              if (imageIcon_ == null) { // change imageIcon_ to bImg if bImg...
                   missingPicture = true;
                   setText("No picture found.");
                   setHorizontalAlignment(CENTER);
                   setOpaque(true);
                   setBackground(Color.black);
              maxUnitIncrement = m;
        public Dimension getPreferredScrollableViewportSize() {
            return getPreferredSize();
        public int getScrollableUnitIncrement(Rectangle visibleRect,
                                              int orientation,
                                              int direction) {
            //Get the current position.
            int currentPosition = 0;
            if (orientation == SwingConstants.HORIZONTAL)
                currentPosition = visibleRect.x;
            else
                currentPosition = visibleRect.y;
            //Return the number of pixels between currentPosition
            //and the nearest tick mark in the indicated direction.
            if (direction < 0) {
                int newPosition = currentPosition -
                   (currentPosition / maxUnitIncrement) *
                   maxUnitIncrement;
                return (newPosition == 0) ? maxUnitIncrement : newPosition;
            } else {
                return ((currentPosition / maxUnitIncrement) + 1) *
                   maxUnitIncrement - currentPosition;
        public int getScrollableBlockIncrement(Rectangle visibleRect,
                                               int orientation,
                                               int direction) {
            if (orientation == SwingConstants.HORIZONTAL)
                return visibleRect.width - maxUnitIncrement;
            else
                return visibleRect.height - maxUnitIncrement;
        public boolean getScrollableTracksViewportWidth() {
            return false;
        public boolean getScrollableTracksViewportHeight() {
            return false;
        public void setMaxUnitIncrement(int pixels) {
            maxUnitIncrement = pixels;
    Next is Corner.java
    import java.awt.*;
    import javax.swing.*;
    public class Corner extends JComponent {
        protected void paintComponent(Graphics g) {
            g.setColor(new Color(230, 163, 4));
            g.fillRect(0, 0, getWidth(), getHeight());
    Next is Rule.java
    import java.awt.*;
    import javax.swing.*;
    public class Rule extends JComponent {
        public static final int INCH = Toolkit.getDefaultToolkit().
                getScreenResolution();
        public static final int HORIZONTAL = 0;
        public static final int VERTICAL = 1;
        public static final int SIZE = 30;
        public int orientation;
        public boolean isMetric;
        private int increment;
        private int units;
        public Rule(int o, boolean m) {
            orientation = o;
            isMetric = m;
            setIncrementAndUnits();
        public void setIsMetric(boolean isMetric) {
            this.isMetric = isMetric;
            setIncrementAndUnits();
            repaint();
        private void setIncrementAndUnits() {
            if (isMetric) {
                units = (int)((double)INCH / (double)2.54); // dots per centimeter
                increment = units;
            } else {
                units = INCH;
                increment = units / 2;
        public boolean isMetric() {
            return this.isMetric;
        public int getIncrement() {
            return increment;
        public void setPreferredHeight(int ph) {
            setPreferredSize(new Dimension(SIZE, ph));
        public void setPreferredWidth(int pw) {
            setPreferredSize(new Dimension(pw, SIZE));
        protected void paintComponent(Graphics g) {
            Rectangle drawHere = g.getClipBounds();
            // Fill clipping area with dirty brown/orange.
            g.setColor(new Color(230, 163, 4));
            g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
            // Do the ruler labels in a small font that's black.
            g.setFont(new Font("SansSerif", Font.PLAIN, 10));
            g.setColor(Color.black);
            // Some vars we need.
            int end = 0;
            int start = 0;
            int tickLength = 0;
            String text = null;
            // Use clipping bounds to calculate first and last tick locations.
            if (orientation == HORIZONTAL) {
                start = (drawHere.x / increment) * increment;
                end = (((drawHere.x + drawHere.width) / increment) + 1)
                      * increment;
            } else {
                start = (drawHere.y / increment) * increment;
                end = (((drawHere.y + drawHere.height) / increment) + 1)
                      * increment;
            // Make a special case of 0 to display the number
            // within the rule and draw a units label.
            if (start == 0) {
                text = Integer.toString(0) + (isMetric ? " cm" : " in");
                tickLength = 8;//10;
                if (orientation == HORIZONTAL) {
                    g.drawLine(0, SIZE-1, 0, SIZE-tickLength-1);
                    g.drawString(text, 2, 21);
                } else {
                    g.drawLine(SIZE-1, 0, SIZE-tickLength-1, 0);
                    g.drawString(text, 9, 10);
                text = null;
                start = increment;
            // ticks and labels
            for (int i = start; i < end; i += increment) {
                if (i % units == 0)  {
                    tickLength = 7;//10;
                    text = Integer.toString(i/units);
                } else {
                    tickLength = 4;//7;
                    text = null;
                if (tickLength != 0) {
                    if (orientation == HORIZONTAL) {
                        g.drawLine(i, SIZE-1, i, SIZE-tickLength-1);
                        if (text != null)
                            g.drawString(text, i-3, 21);
                    } else {
                        g.drawLine(SIZE-1, i, SIZE-tickLength-1, i);
                        if (text != null)
                            g.drawString(text, 9, i+3);
    Here is TooAwoo.html
    <HTML>
    <HEAD>
    <TITLE>TooAwoo</TITLE>
    </HEAD>
    <BODY>
    <APPLET archive="TooAwoo.jar" code="TooAwoo" width=1024 height=800>
    Your browser does not support Java, so nothing is displayed.
    </APPLET>
    </BODY>
    </HTML>
    */Total number of lines: 486
    Weight: 15 199 bytes
    Total number of files: 5
    TooAwoo.java
    ScrollablePicture.java
    Corner.java
    Rule.java
    TooAwoo.html
    ... in that order in my code
    The major default is: I cannot have that BuffuredImage at the left of the screen if run using bImp at line 91 of TooAwoo.java.
    Minor bug: the JToggle button (inch/cm) does not fires-up correctly. Nothing change.
    Anyway feel free to fire at me if you believe its a good strategy. I will remain very positive to all comments and suggestions.
    Thanks.
    dimitryous r.

  • Performance of ImageIO.read with jpeg files

    Hi all... I'm pulling my hair out trying to get a seemingly trivial task to work fast in Java. I'm trying to read in a set of jpeg files, and all I really want out of the files (for now) is width and height. The code I'm testing is:
    for(int i = 0; i < fileList.length; i++)
    ImageInputStream iis = ImageIO.createImageInputStream(fileList);
    BufferedImage bi = ImageIO.read(iis);
    The size of the files I'm trying to read varies from between 80k and 150k. Now get this... here's a real shocker for all you jdk1.4.0 fans out there... the ImageIO.read() method takes as long as 4 seconds to read each file! I've got the standard, plain vanilla jdk1.4.0 running on Redhat 7.1, so I'm wondering if this is an issue with the native code method com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(). The reason I think this is the case is two-fold: 1) I ran -Xrunhprof on this app, and a full 20% of the cpu time is spent in that method. Another 15% is spent in sun.awt.color.CMM.cmmColorConvert(). 2) The same code ran against a directory filled with GIF files runs blazingly fast... the first image decoded takes a second or so, but the next few take milliseconds to decode.
    Is there some optimized native code jpeg readers that I perhaps didn't download? The documentation on this site, to put it bluntly, SUCKS. It's impossible to find any information without resorting to multiple searches, so I highly doubt that I've actually installed everything I should have just by downloading the one installation file for linux. (not the RPM, the one that lets you put it where you want to).
    Any hints or outright solutions to getting jpeg files to be read any faster than this? This shouldn't be rocket science... Every application I've ever seen on any platform up until now can run circles around my pitiful 2 lines of code.
    Thanks for your help!

    you see....I use the ImageReader.readAll(pageIndex, defReadParam) to read from page 'm' to 'n'. The overall performance (speed) is ok. But, the thing is, the thing pauses for some 15 secs approx to read the first page. Then on, it is QUITE fast. Now, if I need to read 500 pages, then the efficiency will be good. But for a single page? The 15 secs is be too long. Anyway I am trying to read a tiff file (which is not too resolute). Guess the first call does smells the ecnoding format to prepare for decoding, etc...But what I want to know is, is there a way to bring down this time. If not, is there any other way to read a tiff page more efficiently? Actually I need to read some pages & write them to a stream...thats all.

  • ImageIcon vs. BufferedImage

    I'm making an applet that will be using a fair number of transparent gifs (a total of ~5-20 megs), and don't know which type of image object would be best suited. Each image will only be a few kilobytes in size and only a few of them need to be displayed at any given time (but the set being displayed will change every now and then).
    I need thumbmails to be displayed centered in two columns and then displayed in full size seperately. To do this, I'm currently using JLabels with ImageIcons for the thumbnails. I change the set being displayed by using 'myJLabel.setIcon(myImageIcon)'. I have not yet implement the part to make them display at full size. Would I have to use something like this:
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(myImageIcon.getImage(), x, y, this);
    Would this create a new Image object? And hence slow the applet (or would it be unnoticable if it's only a few images)? I need to be able to display the image at precise coordinates.
    Would using BufferedImages better suite my needs? I understand that they will perform faster, but I'm not sure if they might cause a problem in terms of storage space. When a BufferedImage is created, is it stored in the user's computer's RAM or their local drive? How about ImageIcons, where are they stored? If the images total 5-20 megs, will either of these methords cause a problem?

    Hi,
    I'm making an applet that will be using a fair number
    of transparent gifs (a total of ~5-20 megs), and don't
    know which type of image object would be best suited.
    Each image will only be a few kilobytes in size and
    only a few of them need to be displayed at any given
    time (but the set being displayed will change every
    now and then).Normally, I would say definitely use ImageIcons because the images that they create can be hardware accelerated behind the scenes. However, transparency currently is not accelerated. This means that most likely, the images stored inside your ImageIcons, are going to be BufferedImages anyway :-)
    >
    I need thumbmails to be displayed centered in two
    columns and then displayed in full size seperately. To
    do this, I'm currently using JLabels with ImageIcons
    for the thumbnails. I change the set being displayed
    by using 'myJLabel.setIcon(myImageIcon)'. I have not
    yet implement the part to make them display at full
    size. Would I have to use something like this:
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(myImageIcon.getImage(), x, y, this);
    }Sure, that's fine! ImageIcon is not going to create a new image every time. You can make the image larger too by using:
    g.drawImage(image, x, y, w, h, this);
    My article on The Swing Connection talks about a couple of the drawImage calls:
    http://java.sun.com/products/jfc/tsc/articles/swing2d/index.html
    >
    Would this create a new Image object? And hence slow
    the applet (or would it be unnoticable if it's only a
    few images)? I need to be able to display the image at
    precise coordinates.
    Would using BufferedImages better suite my needs? I
    understand that they will perform faster, but I'm not
    sure if they might cause a problem in terms of storage
    space. When a BufferedImage is created, is it stored
    in the user's computer's RAM or their local drive? How
    about ImageIcons, where are they stored? If the images
    total 5-20 megs, will either of these methords cause a
    problem?BufferedImages are stored in RAM, as are the images inside ImageIcons. ImageIcons CAN be faster for non-transparent images. They may currently perform slightly slower for transparent images. You might just have to test it out.
    By the way, if you find you're running out of memory (ie. OutOfMemoryError), you can increase the Java heap size when you run your application.
    Use the -Xms and -Xmx flags to set the initial and maximum heap sizes.
    For example, to give your application 64 Megs of ram to start and allow up to 128 Megs:
    java -Xms64M -Xmx128M YourClassName
    Good luck!
    Shannon Hickey (Swing Team)

  • Performance trouble on repaint

    Hello there!
    I've got a GUI question for you.
    Is there a way to display (repaint) just what is seen in the clipping area of a Graphics?
    That is to say, if I have a Shape that "crosses" the clipping area (the shape is bigger than the visible area, and just a part of it will be displayed), is there a way to draw just the visible part of the Shape?
    Because in my soft, the user can draw shapes on a picture, and can also perform a zoom. The problem is that when we have a high zoom factor, it seems that the Grapsics takes a long time to draw the Shapes.
    Moreover, for some particular reasons, we have to "repaint" really frequently the frame, so this problem is really troublesome.
    Here is the code used to draw the Shapes (used for each Shape drawn on the picture):
         public void draw(Graphics2D g2d, AffineTransform aff,
                   Color shapeBackground, Color shapeOutline, float shapeTransparency,
                   float shapeThickness, float[] shapeStyle, String texturePath,
                   Color splitBackground, Color splitOutline, float splitTransparency) {
              g2d.setStroke(new BasicStroke(shapeThickness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10.0f, shapeStyle, 1));
              g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, shapeTransparency));
              Shape rat = aff.createTransformedShape(shape);
              g2d.setColor(shapeBackground);
              // gestion de la texture
              if (texturePath != null && texturePath.length() > 0) {
                   BufferedImage img;
                   img = ImageFilesReader.read(texturePath);
                   if (img != null) {
                        g2d.setPaint(new TexturePaint(img, rat.getBounds2D()));
              g2d.fill(rat);
              g2d.setColor(shapeOutline);
              if (shapeStyle == CustomizeROIAppearanceDialog.EMPTY_STROKE) {
                   g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0f));
              else {
                   g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
              g2d.draw(rat);
              g2d.setStroke(new BasicStroke());
              if (isSelected){
                   split.draw(g2d,aff,splitBackground,splitOutline,splitTransparency);
    If it is not possible, do you think that performing a double-buffering strategy could improve the speed of the repaint?...
    Thanks a lot!

    In fact, I don't ask the Graphics to repaint outside of my component. I have a picture displayed in a JScrollPane, so some parts of my picture and some of my Shapes can lay outside of the visible zone... And so, I would like to draw just the parts of the Shapes that are visible (not the whole Shapes that have visible part, but just ht visible part, if it's possible)
    You said :
    "Perhaps you could also try manually clipping the shape before you pass it to the affine transform. Or only pass the visible bounds when you set the texture paint. But those are just guesses. "
    How can I do that?
    Thanks!

  • BufferedImage size

    Hi,
    I am developing a swing application which needs to be able to draw thousands of lines on the screen. The line count may well reach 200K although many of the lines are very small. I need the ability to scale the lines as required.
    Obviously drawing each line at paint time is very time consuming and so I currently draw them to a BufferedImage. This has resulted in a very acceptable image on screen which repaints very fast. However, the image can easily grow in excess of 6000 pixels square. The memory required for this runs at 100 - 150M. If I use transparency this figure is even larger (which I really need to do).
    Why does a BufferedImage use so much memory? Is there a way of producing similar results with a much smaller memory use?
    One thing to note is that all the lines that are drawn are a single colour and hopefully on a transparent background.
    Is there a way of storing an image in a raw form and then performing minimal processing to it at draw time?
    Is there a way to improve the speed at which Java draws directly to the screen (greatly).
    Thanks in advance for any suggestions.
    Dan.

    ninja600 wrote:
    Hi,
    I am developing a swing application which needs to be able to draw thousands of lines on the screen. The line count may well reach 200K although many of the lines are very small. I need the ability to scale the lines as required.
    Obviously drawing each line at paint time is very time consuming and so I currently draw them to a BufferedImage. This has resulted in a very acceptable image on screen which repaints very fast. However, the image can easily grow in excess of 6000 pixels square. The memory required for this runs at 100 - 150M. If I use transparency this figure is even larger (which I really need to do).Sounds right to me. Such a large image will produce a large memory footprint.
    Why does a BufferedImage use so much memory? It doesn't use any more than any other format.
    Is there a way of producing similar results with a much smaller memory use?You could compress the image I suppose, but you'd lose quality and take a hit on performance. I usually only compress and image when I'm saving it to disk.
    One thing to note is that all the lines that are drawn are a single colour and hopefully on a transparent background.Well that would certainly compress nice, but not sure that's what you want.
    Is there a way of storing an image in a raw form and then performing minimal processing to it at draw time?Not sure what you mean.
    Is there a way to improve the speed at which Java draws directly to the screen (greatly).Depends on what you are doing. Have you looked at VolitileImage?

  • Performance problems with AlphaComposite

    Hi,
    I'm writing an application using Graphics2D that on the background has a grid that has been baked on a BufferedImage, which is first drawn using drawImage and on top of that (if the user draws a selection) a selection that is an Area object. The selection should be partially transparent so I used AlphaComposite as follows:
    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
    g2.setComposite(ac);
    g2.setPaint(new Color(168, 199, 232));
    g2.fill(ResourceManager.getSelection());
    g2.setPaint(new Color(51,153,255));
    g2.draw(ResourceManager.getSelection()); // Draw the border.
    g2.setComposite(AlphaComposite.SrcOver); // Reset to opaque.All really basic but I must be doing something wrong here because it takes around 6-7 ms to render it, while the rest of the scene takes no more than 2-3. Commenting all the AlphaComposite code reduces rendering time of it to 0.1-0.4 ms (depending on the size of the selection).
    I don't think that there's any more information that I could give you that's relevant here. I'm just wondering if I'm doing something wrong here or if the whole transparency thing is really this slow.

    Thanks :)
    I'm currently rendering to a JPanel that is used as a canvas, which - as a Swing component - is double buffered and I assume that the buffer which I'm drawing on is hardware accelerated, unless there's extra steps that I need to take to make it so. I honestly don't know what's hardware accelerated by default and what's not. I set setDoubleBuffered to false and used a VolatileImage as a buffer (which I think is always accelerated) and that still gives me awful performance.
    But 6-7ms is an expected time for software rendering of transparency? Still seems like an awful long time.

  • Profiling and performance optimization

    This subject realy sucks in the CLDC/j2me world. Profiling in the emulator is useless, and on the device, you simply can't do it. System.currentTimeMillis() might give you some hits, but is the overhead of printing this (in my case to a comm port) is to large for the testet function, you are out of options... What to do then?
    Well, with this topic, I would like to ask for some help om the possibilities of profiling j2me devices.
    I'm currently working on a compression algorithm te compress log data. I found one that doesn't use a lot of memory and managed to incorporate it in my CLDC programme: ( It uses Arithmatic compression, got it from http://www.mandala.co.uk/biac/index.html ).
    The problem is: Althouth the source is very compact and fairly simple, it still is very slow om my device (they claim it can do about 700 lines of java code/sec, but I think it is a bit more).
    Solution: optimize, but how if you don't know where to start? Well, the algorithm is simple enough to have a look at it, and optimize by trail and error... luckilly I remenberd some things I leaned on a cource about image manipulation (in C).
    So, next is a list of simple things you can do to to optimze your code, in sections where every byte of code executed is crucial:
    - try to find out what code is executed often or takes a lot of time; look at loops and calculations.
    - instead of x*2 use x<<1, instead of x/2 use x>>1, etc.
    - try to manually unroll loops (you might first try out how often the loop runs to test who for to unroll it
    - if the same calculation is used more than ones, just caclulate the value ones, and then just use that value in the other calculations in stread of caclulating it over and over. If those values are static, declare them static.
    - if possible manually inline short functions. You might even use a preprocessor (in cobination with ant or somthing) and use macro's
    - simplt try to do more with less code
    - if you often devide though a fixed number, try to multiply with the inverted (thisis not always possible in j2me because only integer math is available). This is faster on most devices.
    - Use array's if you have to acces lare amounts of data. Vectors and such are much slower.
    - Use compiler and obfuscator to optimize and shrink your code.
    Most of them are very obvious, but often you just forget about it.
    Well, all in all, my compression algorithm got at fair bit faster, but it is still to slow. I guess I'm going to tweak it a little more ;)
    Hope you guys can do something with it. If you have some more tips, just let me know!

    Good day,
    As I tried, there are two ways of doing printPreview.
    To handle this problem, add only one page at a time.
    To browse through the page use Prev Page, Nexe Page buttons in the toolbar.
    1) BufferedImage - occupies memory .
    Class PagePreview extends JPanel
    public void paint(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    g.drawImage(m_img, 0, 0, this);
    paintBorder(g);
    This gives better performance, but consumes memory.
    2) getPageGraphics in the preview panel . This occupies less memory, but re-paint the graphics everytime when paint(Graphics g) is called.
    Class PagePreview extends JPanel
    public void paint(Graphics g)
    g.setColor(Color.white);
    RepaintManager currentManager = RepaintManager.currentManager(this);
    currentManager.setDoubleBufferingEnabled(false);
    Graphics2D g2 = scrollPanel.getPageGraphics();
    currentManager.setDoubleBufferingEnabled(true);
    g2.dispose();
    This addresses memory problem, but performance is better.
    Is there any additional info from you?
    Good Luck,
    Kind Regards,
    Krish

  • Help with BufferedImage - Graphics updating

    Hello All-
    I will try to explain the best I can, still new to Java2D so little confused
    Hopefully the explanation makes a little bit of sense....
    I have a tabbedPane, one tab with no graphics and the other tab full of graphics
    The tab with the graphics on it is basically a bunch of rectangles that will change color depending on real time data I am pulling from a Mysql DB
    For sake of performance I only want to have to repaint those rectangles when the data from the DB changes (i.e. repaint the rectangles when the bit changes from 1=good to 0=bad)
    Any help on how to start implementing this would be absolutely wonderful
    or if I could explain something any better please ask.
    Thank you in advance
    Janduzerbots

    If you're thinking of just grabbing the graphics image of some component on the fly for rendering, that
    wouldn't work well. Here is a link to some tips on doing your own drawing.
    Again, yes, you may have to define your own component class. The only other alternative I can think of is to have a JLabel
    that has an ImageIcon that holds your BufferedImage, and you update this by calling repaint after updating
    the BufferedImage.

Maybe you are looking for

  • How to find rowid of locked rows?

    Hello All, I have the "before update trigger" I want to know the rowid of all the locked row before update so that I dont try to update the same row which is locked by some other user. In Ask Tom forum I have seen how to know the rowid of locked row,

  • Adobe Indesign CS6 not finding fonts

    Dear Support, Adobe Indesign is not detecting the font arial narrow bold, narrow italic, please can you inform what to do. I have reinstalled the font in the windows\fonts folder restarted and still experience issues. I have reinstalled adobe indesig

  • Weblogic Threading Issue

    Dear All, We have a situation (very strange one). Here is the setup. Our application is written in struts 1.1. The configuration is as follow. Internet --> Sun One Web Server (7.0) --> WebLogic (10) ---> Database Our application has one page where we

  • After sharing, edited images become distorted.

    When applying filters to images and sequently sharing them, to mail, to iphoto library, ... imege goes wrong. It looks like sharing does not work. It produces distortion. Anyone having same problem. Suggestions?

  • When will sample iPhone 6 be in stores to view?

    When will these be in stores to view size...not to purchase?