Get image properties (width and height)

Hi there,
Does anyone know if there is a way that I could get the width and height of an image to be displayed in a JSP.

Image has methods to get the width & height.

Similar Messages

  • How do i get the max width and height?

    Hey
    I want to get the max width and height, so my desktoppanes size can be set automatically.
    I know i should use getBounds but i cant find a concrete example on goole, on how to use it.
    Can someone point me in the right direction, with an example?

    Ok, assuming you want to get the screen resolution, i.e. 1024 x 768.
    You will need these imports:
    import java.awt.Dimension;
    import java.awt.Toolkit;and this line of code:
    Dimension myScreen =  Toolkit.getDefaultToolkit().getScreenSize() ;You can now use myScreen.width and myScreen.height to access the height and width of your screen's resolution. (width = 1024, height = 768 in my case)
    Hope this helps,
    Stern
    Edited by: Stern on Apr 13, 2008 6:49 AM

  • Images with width and height

    There is a way to insert an image inside of the html code
    with width and height already? I mean, now, if I want to insert an
    image at the code, goes only <img src="images/test.gif" /> I
    d like that if I insert an image it goes as: <img
    src="images/canto_topo.gif" width="8" height="29" />
    is possible in dreamwaver to do that?
    Thanks!
    Vismona

    If you insert the image using the "Insert Image" function, DW
    will
    automatically insert the width and height.
    Or, if you'd rather insert them the way you are, in the
    Property Inspector
    on the far left, click the dimensions next to the Image
    field, and DW will
    automatically add (or correct) the width and height.
    Hope that helps,
    Patty Ayers | www.WebDevBiz.com
    Free Articles on the Business of Web Development
    Web Design Contract, Estimate Request Form, Estimate
    Worksheet
    "Vismona" <[email protected]> wrote in
    message
    news:gc60ut$nmv$[email protected]..
    > There is a way to insert an image inside of the html
    code with width and
    > height
    > already? I mean, now, if I want to insert an image at
    the code, goes only
    > <img
    > src="images/test.gif" /> I d like that if I insert an
    image it goes as:
    > <img
    > src="images/canto_topo.gif" width="8" height="29" />
    >
    > is possible in dreamwaver to do that?
    >
    > Thanks!
    > Vismona
    >

  • How to get full screen width and height  when using CustomItem not canvas ?

    hi..
    I have to append one Textfield and a CustomItem ( as canvas) for painting on a single form.
    I have to draw a rectangle in CustomItem in full Screen width of mobile .
    So I have to know the screen width of mobile for drawing a rectangle.
    Please Suggest me. how can I do that ?
    Thanks

    Did you check javax.microedition.lcdui.Form.getWidth() and javax.microedition.lcdui.Form.getHeight() methods?
    Atul

  • Get image properties not in Metadata

    Hi,
    I use the XMPScript API with a JScript for Photoshop to get files image properties (width and height) before to import them. It work well but SGI and OpenEXR files don't have width/heigth information in the Metadata. I would like to know if it's possible to figure out this problem.
    For example, how ACDSee can get this information for SGI files ?
    Thanks

    Bridge has an alternate interface for accessing metadata from image files. You may be able to get the values you need that way. The other alternative is to call exiftool via app.system(), have it dump its results to a text file and see if what you need is in there.
    -X

  • Draw rotated image to given width and height

    Problem, if an image where width and height aren't equal is rotated and drawn again, the image is not drawn (stretched) to the full width.
    Below is an example to illustrate my problem. The top image is stretched to the full width, the other aint.
    Example picture: http://www.google.nl/intl/nl_nl/images/logo.gif
    What am I doing wrong??
    Greet Retep
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.awt.image.BufferedImageOp;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    public class Test2 extends Frame{
         public static void main(String[] args)
              try {
                   new Test2();
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public Test2() {
              super("Rotate picture");
              add(new RotateTest());
            addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 300);
            setVisible(true);
         class RotateTest extends JComponent {
             public void paint(Graphics g) {
                 Graphics2D g2d = (Graphics2D)g;
                 try {
                        BufferedImage image = ImageIO.read(new BufferedInputStream(new FileInputStream("C:/logo.gif")));
                        AffineTransform affineTransForm = new AffineTransform();
                      affineTransForm.rotate(Math.toRadians(270), image.getWidth(), 0); 
                      //flip
                      //affineTransForm.translate(0, image.getHeight());
                      //affineTransForm.scale(1, -1);
                      BufferedImageOp bufferedImageOp = new AffineTransformOp(affineTransForm,
                              AffineTransformOp.TYPE_BICUBIC);
                      BufferedImage image2 = bufferedImageOp.filter(image, null);
    //                  BufferedImage tempImage = new BufferedImage(image.getWidth(),image.getHeight(), image2.getType());
    //                Graphics2D graphics2D = tempImage.createGraphics();
    //                graphics2D.drawImage(image2, 0, 0, null);
    //                graphics2D.dispose();
                      g2d.drawImage(image, 5, 15, 280, 50, null);
                      g2d.drawImage(image2, 5, 70, 280, 50, null);
                      //g2d.drawImage(tempImage, 5, 125, 280, 50, null);
                      //g2d.drawImage(image, affineTransForm, null);
                      g2d.drawRect(5, 15, 280, 50);
                      g2d.drawRect(5, 70, 280, 50);
                   } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
    }

    Let's see if this helps...
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
    public class T2Rx extends Frame {
        public static void main(String[] args) {
            try {
                new T2Rx();
            } catch (Exception e) {
               e.printStackTrace();
        public T2Rx() {
            super("Rotate picture");
            add(new RotateTest());
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            setFont(new Font("default", Font.PLAIN, 24));
            setSize(300, 375);
            setLocation(200,200);
            setVisible(true);
        class RotateTest extends JComponent {
            BufferedImage image;
            RotateTest() {
                // You only need to do this one time. Save the image in a
                // a member variable so you can access it whenever you want.
                try {
                    image = ImageIO.read(new BufferedInputStream(
                                         new FileInputStream("logo.gif")));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
            protected void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                int w = getWidth();
                int h = getHeight();
                BufferedImage scaled = scaleTo(image, 280, 50);
                int iw = scaled.getWidth();
                int ih = scaled.getHeight();
                double x = (w - iw)/2.0;
                double y = 1;
                g2.drawImage(scaled, (int)x, (int)y, this);
                g2.draw(new Rectangle2D.Double(x, y, iw, ih));
                double theta = Math.PI*3/2;
                x = (w - ih)/2.0;
                y = (ih + iw)/2.0 + 1;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                at.rotate(theta, iw/2.0, ih/2.0);
                g2.drawRenderedImage(scaled, at);
                g2.draw(at.createTransformedShape(new Rectangle2D.Double(0, 0, iw, ih)));
        private BufferedImage scaleTo(BufferedImage src, int w, int h) {
            //System.out.printf("type = %d%n", src.getType());
            // This type gives a better appearance after scaling.
            int type = BufferedImage.TYPE_INT_RGB;
            BufferedImage out = new BufferedImage(w, h, type);
            Graphics2D g2 = out.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.setBackground(getBackground());
                             //java.awt.Color.pink);  // just checking
            g2.clearRect(0, 0, w, h);
            double xScale = (double)w/src.getWidth();
            double yScale = (double)h/src.getHeight();
            double scale = Math.min(xScale, yScale);    // scale to fit
                           //Math.max(xScale, yScale);  // scale to fill
            double x = (w - scale*src.getWidth())/2;
            double y = (h - scale*src.getHeight())/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.scale(scale, scale);
            g2.drawRenderedImage(src, at);
            g2.dispose();
            return out;
    }

  • How to get width and height of a jpg file ?

    Hello,
    I'm trying to insert a jpg file in a blob field on my database. The problem is that I need to get the file width and height in pixels. My class does not have a graphic interface, it's a batch. Does anybody has an idea of how can I do that ?
    tia.

    Write a jpeg decoder that can figure out how to determine the width/height of a jpeg file? Google it.
    Or if you're really lazy, load each jpeg using the
    Toolkit.loadImage( URL ) function and use getWidth/getHeight from there, but that's slow.

  • Getting image properties

    anyone know of any jsp code that i can use to get an image's width and height?
    (the image is stored externally to the jsp and is referenced with a url)

    Use the ImageIcon class to load the image from the URL and call the methods to get the width/height.

  • How can I get the image width and height stored in database?

    Hi!I write s servlet to display images store in database.but how can I get the image width and height?

    Have you tryed using PJA or a similar library?
    I presume you get java.lang.NoClassDefFoundError on the line :
    Toolkit.getDefaultToolkit();?

  • Get width and height of a dynamically loaded image once it's done loading?!

    hello : :
    well... i'm taking my first shots at flex after programming
    in flash for a year now. it's been fun and i've been picking up on
    things pretty well (or so i think), but i come across something
    today that i used to be able to do in my as2 programming and don't
    know how to do in as3...
    in flex, i'm loading an image into an image control (by using
    "myImgControl.load(urlString)"). i have a "complete" parameter on
    the image control that calls a function just fine after the image
    is loaded, but if i try and check the hight and width of the loaded
    image once it loads, it comes back as zero. how can i get the
    height and width of the image after it's loaded?!
    in flash/as2 i used to do this little trick/work-around i
    found in a forum (kirupa.com, i think) to find out the width and
    height once the loaded image listener checked the loading process
    and came back "complete"... in the code below, "imgLoader" is the
    movieClip the image was loaded using
    imgLoaderListener.loadClip(urlString, imgLoader).
    quote:
    iTot = imgLoader.getBytesTotal();
    iLoad = imgLoader.getBytesLoaded();
    if (iLoad == iTot && iTot > 4) {
    imgH = imgLoader._height;
    imgW = imgLoader._width;
    that all make sense?!
    basically, it's as simple as this: i need to find something
    similar to the above for as3 that will tell me the width and height
    of a dynamically loaded image after it's done loading...
    so there ya have it. i appreciate any help any of you can
    throw my way! thank you so much for even reading this!
    : : michael

    I assume you have probably already figured this out, but just
    in case, there should be an event to listen for after which you can
    get the height and width information successfully. I can't remember
    the exact name, however. Experiment and see which one works
    time-wise.

  • The crawled property of Image width and height - is there a differnce when the image is png format?

    Hi,
    We are indexing file share with images and get the properties of Image Width, Image Height, Image Size (we show it as refiners in SharePoint after make it managed properties). Somehow when the picture is png format - we see only Size but not height and width.
    Is that any setting that should be done in the file share (when i select an image in the windows explorer window i can see all its properties, and it seems that png files do expose the width and height properties
    keren tsur

    Hi  Keren,
    According to your description, my understanding is that when you tried to  crawl file share with images, the ows_ImageWidth and ows_ImageHeight crawled property for PNG  file could not be generated.
    For your issue, I can reproduce your issue in my SharePoint 2013 environment. For a workaround, you can upload the PNG images into SharePoint images Library and they would work fine.
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • Java returning incorrect values for width and height of a Tiff image

    I have some TIFF images (sorry, I cannot post them b/c of there confidential nature) that are returning the incorrect values for the width and height. I am using Image.getWidth(null) and have tried the relevant methods from BufferedImage. When I open the same files in external viewers (Irfanview, MS Office Document Imaging) they look fine and report the "correct" dimensions. When I re-save the files, my code works fine. Obviously, there is something wrong with the files, but why would the Java code fail and not the external viewers? Is there some way I can detect file problems?
    Here is the code, the relevant section is in the print() routine.
    * ImagePrinter.java
    * Created on Feb 27, 2008
    * Created by tso1207
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.print.PageFormat;
    import java.awt.print.PrinterException;
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.FileImageInputStream;
    import javax.imageio.stream.ImageInputStream;
    import com.shelter.io.FileTypeIdentifier;
    public class ImagePrinter extends FilePrintable
       private final ImageReader _reader;
       private final int _pageCount;
       private final boolean _isTiff;
       //for speed we will hold current page info in memory
       private Image _image = null;
       private int _imgWidth = 0;
       private int _imgHeight = 0;
       private int _currentPage = -1;
       public ImagePrinter(File imageFile) throws IOException
          super(imageFile);
          ImageInputStream fis = new FileImageInputStream(getFile());
          Iterator readerIter = ImageIO.getImageReaders(fis);
          ImageReader reader = null;
          while (readerIter.hasNext())
             reader = (ImageReader) readerIter.next();
          reader.setInput(fis);
          _reader = reader;
          int pageCount = 1;
          String mimeType = FileTypeIdentifier.getMimeType(imageFile, true);
          if (mimeType.equalsIgnoreCase("image/tiff"))
             _isTiff = true;
             pageCount = reader.getNumImages(true);
          else
             _isTiff = false;
          _pageCount = pageCount;
       public int print(java.awt.Graphics g, java.awt.print.PageFormat pf, int pageIndex)
          throws java.awt.print.PrinterException
          int drawX = 0, drawY = 0;
          double scaleRatio = 1;
          if (getCurrentPage() != (pageIndex - getPageOffset()))
             try
                setCurrentPage(pageIndex - getPageOffset());
                setImage(_reader.read(getCurrentPage()));
                setImgWidth(getImage().getWidth(null));
                setImgHeight(getImage().getHeight(null));
             catch (IndexOutOfBoundsException e)
                return NO_SUCH_PAGE;
             catch (IOException e)
                throw new PrinterException(e.getLocalizedMessage());
             if (!_isTiff && getImgWidth() > getImgHeight())
                pf.setOrientation(PageFormat.LANDSCAPE);
             else
                pf.setOrientation(PageFormat.PORTRAIT);
          Graphics2D g2 = (Graphics2D) g;
          g2.translate(pf.getImageableX(), pf.getImageableY());
          g2.setClip(0, 0, (int) pf.getImageableWidth(), (int) pf.getImageableHeight());
          scaleRatio =
             (double) ((getImgWidth() > getImgHeight())
                ? (pf.getImageableWidth() / getImgWidth())
                : (pf.getImageableHeight() / getImgHeight()));
          //check the scale ratio to make sure that we will not write something off the page
          if ((getImgWidth() * scaleRatio) > pf.getImageableWidth())
             scaleRatio = (pf.getImageableWidth() / getImgWidth());
          else if ((getImgHeight() * scaleRatio) > pf.getImageableHeight())
             scaleRatio = (pf.getImageableHeight() / getImgHeight());
          int drawWidth = getImgWidth();
          int drawHeight = getImgHeight();
          //center image
          if (scaleRatio < 1)
             drawX = (int) ((pf.getImageableWidth() - (getImgWidth() * scaleRatio)) / 2);
             drawY = (int) ((pf.getImageableHeight() - (getImgHeight() * scaleRatio)) / 2);
             drawWidth = (int) (getImgWidth() * scaleRatio);
             drawHeight = (int) (getImgHeight() * scaleRatio);
          else
             drawX = (int) (pf.getImageableWidth() - getImgWidth()) / 2;
             drawY = (int) (pf.getImageableHeight() - getImgHeight()) / 2;
          g2.drawImage(getImage(), drawX, drawY, drawWidth, drawHeight, null);
          g2.dispose();
          return PAGE_EXISTS;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since version XXX
        * @return
       public int getPageCount()
          return _pageCount;
       public void destroy()
          setImage(null);
          try
             _reader.reset();
             _reader.dispose();
          catch (Exception e)
          System.gc();
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public Image getImage()
          return _image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgHeight()
          return _imgHeight;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgWidth()
          return _imgWidth;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param image
       public void setImage(Image image)
          _image = image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgHeight(int i)
          _imgHeight = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgWidth(int i)
          _imgWidth = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getCurrentPage()
          return _currentPage;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setCurrentPage(int i)
          _currentPage = i;
    }Edited by: jloyd01 on Jul 3, 2008 8:26 AM

    Figured it out. The files have a different vertical and horizontal resolutions. In this case the horizontal resolution is 200 DPI and the vertical is 100 DPI. The imgage width and height values are based on those resolution values. I wrote a section of code to take care of the problem (at least for TIFF 6.0)
       private void setPageSize(int pageNum) throws IOException
          IIOMetadata imageMetadata = _reader.getImageMetadata(pageNum);
          //Get the IFD (Image File Directory) which is the root of all the tags
          //for this image. From here we can get all the tags in the image.
          TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);
          double xPixles = ifd.getTIFFField(256).getAsDouble(0);
          double yPixles = ifd.getTIFFField(257).getAsDouble(0);
          double xRes = ifd.getTIFFField(282).getAsDouble(0);
          double yres = ifd.getTIFFField(283).getAsDouble(0);
          int resUnits = ifd.getTIFFField(296).getAsInt(0);
          double imageWidth = xPixles / xRes;
          double imageHeight = yPixles / yres;
          //if units are in CM convert ot inches
          if (resUnits == 3)
             imageWidth = imageWidth * 0.3937;
             imageHeight = imageHeight * 0.3937;
          //convert to pixles in 72 DPI
          imageWidth = imageWidth * 72;
          imageHeight = imageHeight * 72;
          setImgWidth((int) Math.round(imageWidth));
          setImgHeight((int) Math.round(imageHeight));
          setImgAspectRatio(imageWidth / imageHeight);
       }

  • Nested canvas in GridLayout can't get its width and height

    Hello,
    I have a class entitled DisplayCanvas, which will accept some parameters from an invocation in another class including a shape and message parameters. These parameters must be centered in the instance of DisplayCanvas.
    For some reason, when I use this.getWidth() and this.getHeight() within my DisplayCanvas class, I get 0 and 0! I need the width and height in order to center the parameters the user will enter.
    Why does the width and height result at 0? What can I do to get the width and height?
    In my DisplayCanvas class notice the lines:
    canWidth = this.getWidth();
    canHeight = this.getHeight();
    For some reason the result is 0 for each!
    Here is my code for the DisplayCanvas class:
    //import the necessary clases
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    //begin the DisplayCanvas
    public class DisplayCanvas extends Canvas
      //declare private data members to house the width and height of the canvas
      private int canWidth;
      private int canHeight;
      //declare private data members for the shape and message
      private String message;
      private String shape;
      private Color sColor;
      private int sWidth;
      private int sHeight;
      private String font;
      private Color ftColor;
      private int ftSize;
      //declare public data members
      //constructor of DisplayCanvas
      public DisplayCanvas()
         //set the width and height
         canWidth = this.getWidth();
         canHeight = this.getHeight();
         //set all data members to defaults
         message = "";
         shape = "";
         sColor = null;
         sWidth = 0;
         sHeight = 0;
         font = "";
         ftColor = null;
         ftSize = 0;
      } //end the constructor
      //begin the setParams function
      public void setParams(String m, String s, Color c, int w, int h,
                            String f, Color ftC, int ftS)
          //set all private data members of DisplayShape to the arguments
          //this function assumes error checking was done by DemoShape
          message = m;
          shape = s;
          sColor = c;
          sWidth = w;
          sHeight = h;
          font = f;
          ftColor = ftC;
          ftSize = ftS;
      } //end the setParams function
      //begin the public paint function of ShowShape
      public void paint(Graphics g)
          //set and output the shape according to the arguments
          //determine the x and y of the shape
          int x = (canWidth - sWidth) / 2;
          int y = (canHeight - sHeight) / 2;
          //set the color for the graphic object
          g.setColor(sColor);
          //output the shape
          g.drawRect(x, y, sWidth, sHeight);
          //set and output the message according to the arguments
          //set the color and the font for the graphic object
          g.setColor(ftColor);
          g.setFont(new Font(font, Font.PLAIN, ftSize));
          //determine the centering of the message
          //output the message with the settings
          g.drawString(canWidth + " " + canHeight, 10, 10);
      } //end the paint function of ShowShape class
    } //end the DisplayCanvas classHere is my form entry class using the nested DisplayCanvas instance entitled drawCanvas:
    //import the necessary java packages
    import java.awt.*;                  //for the awt widgets
    import javax.swing.*;               //for the swing widgets
    import java.awt.event.*;            //for the event handler interfaces
    //no import is needed for the DisplayCanvas class
    //if in the same directory as the DemoShape class
    public class DemoShape extends JApplet
        //declare private data members of the DemoShape class
        //declare the entry and display panel containers
        private Container entire;           //houses entryPanel and displayCanvas
        private JPanel entryPanel;          //accepts the user entries into widgets
        private DisplayCanvas drawCanvas;   //displays the response of entries
        //required control buttons for the entryPanel
        private JTextField xShapeText, yShapeText, messageText, fontSizeText;
        private ButtonGroup shapeRadio;
        private JRadioButton rect, oval, roundRect;
        private JComboBox shapeColorDrop, fontTypeDrop, fontColorDrop;
        //declare public data members of the DemoShape class
        //init method to initialize the applet objects
        public void init()
            //arrays of string to be used later in combo boxes
            //some are used more than once
            String fonts[] = {"Dialog", "Dialog Input", "Monospaced",
                                "Serif", "Sans Serif"};
            String shapes[] = {"Rectangle", "Round Rectangle", "Oval"};   
            String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
                                "Gray", "Green", "Light Gray", "Magenta", "Orange",
                                "Pink", "Red", "White", "Yellow"};
            //declare variables to assist with the layout
            //these are the left and right justified x coordinates
            int ljX = 10; int rjX = 150;
            //this is the y coordinates for the rows
            int yRow1 = 10;     //the shape rows
            int yRow2 = 40;
            int yRow3 = 60;
            int yRow4 = 130;
            int yRow5 = 150;
            int yRow6 = 210;    //the message rows
            int yRow7 = 240;
            int yRow8 = 260;
            int yRow9 = 300;
            int yRow10 = 320;
            int yRow11 = 360;
            int yRow12 = 380;
            //these are the widths for the text boxes, drop downs
            //message entry,  big message entry and radio buttons
            int tWidth = 30; int dWidth = 100;
            int mWidth = 250; int bmWidth = 250;
            int rWidth = 125;
            //the height is universal, even for the messages!
            int height = 25;
            //set a content pane for the entire applet
            //set the size of the entire window and show the entire applet
            entire = this.getContentPane();
            entire.setLayout(new GridLayout(1, 2));
            //create the entry panel and add it to the entire pane
            entryPanel = new JPanel();
            entryPanel.setLayout(null);
            entire.add(entryPanel);
            //create the display canvas and add it to the entire pane
            //this will display the output
            drawCanvas = new DisplayCanvas();
            entire.add(drawCanvas);       
            //entry panel code
            //add the form elements in the form of rows
            //the first row (label)
            JLabel entryLabel = new JLabel("Enter Shape Parameters:");
            entryPanel.add(entryLabel);
            entryLabel.setBounds(ljX, yRow1, bmWidth, height);
            //second row (labels)
            JLabel shapeTypeLabel = new JLabel("Select Shape:");
            shapeTypeLabel.setBounds(ljX, yRow2, mWidth, height);
            entryPanel.add(shapeTypeLabel);
            JLabel shapeColorLabel = new JLabel("Select Shape Color:");
            shapeColorLabel.setBounds(rjX, yRow2, mWidth, height);
            entryPanel.add(shapeColorLabel);
            //third row (entry)        
            rect = new JRadioButton("Rectangle", true);
            oval = new JRadioButton("Oval", false);
            roundRect = new JRadioButton("Round Rectangle", false);
            rect.setBounds(ljX, yRow3, rWidth, height);
            oval.setBounds(ljX, yRow3 + 20, rWidth, height);
            roundRect.setBounds(ljX, yRow3 + 40, rWidth, height);
            shapeRadio = new ButtonGroup();
            shapeRadio.add(rect);
            shapeRadio.add(oval);
            shapeRadio.add(roundRect);
            entryPanel.add(rect);
            entryPanel.add(oval);
            entryPanel.add(roundRect);       
            shapeColorDrop = new JComboBox(colors);
            shapeColorDrop.setBounds(rjX, yRow3, dWidth, height);
            shapeColorDrop.addFocusListener(new focusListen());
            entryPanel.add(shapeColorDrop);
            //the fourth row (labels)
            JLabel xShapeLabel = new JLabel("Enter Width:");
            xShapeLabel.setBounds(ljX, yRow4, mWidth, height);
            entryPanel.add(xShapeLabel);
            JLabel yShapeLabel = new JLabel("Enter Height:");
            yShapeLabel.setBounds(rjX, yRow4, mWidth, height);
            entryPanel.add(yShapeLabel);
            //the fifth row (entry)
            xShapeText = new JTextField("200", 3);
            xShapeText.setBounds(ljX, yRow5, tWidth, height);
            xShapeText.addFocusListener(new focusListen());
            entryPanel.add(xShapeText);        
            yShapeText = new JTextField("200", 3);
            yShapeText.setBounds(rjX, yRow5, tWidth, height);
            yShapeText.addFocusListener(new focusListen());
            entryPanel.add(yShapeText);
            //the sixth row (label)
            JLabel messageLabel = new JLabel("Enter Message Parameters:");
            messageLabel.setBounds(ljX, yRow6, bmWidth, height);
            entryPanel.add(messageLabel);
            //the seventh row (labels)   
            JLabel messageEntryLabel= new JLabel("Enter Message:");
            messageEntryLabel.setBounds(ljX, yRow7, mWidth, height);
            entryPanel.add(messageEntryLabel);
            //the eighth row (entry)
            messageText = new JTextField("Enter your message here.");
            messageText.setBounds(ljX, yRow8, mWidth, height);
            messageText.addFocusListener(new focusListen());
            entryPanel.add(messageText);
            //the ninth row (label)
            JLabel fontTypeLabel = new JLabel("Select Font:");
            fontTypeLabel.setBounds(ljX, yRow9, mWidth, height);
            entryPanel.add(fontTypeLabel);
            JLabel fontColorLabel = new JLabel("Select Font Color:");
            fontColorLabel.setBounds(rjX, yRow9, mWidth, height);
            entryPanel.add(fontColorLabel);
            //the tenth row (entry)
            fontTypeDrop = new JComboBox(fonts);
            fontTypeDrop.setBounds(ljX, yRow10, dWidth, height);
            fontTypeDrop.addFocusListener(new focusListen());
            entryPanel.add(fontTypeDrop);       
            fontColorDrop = new JComboBox(colors);
            fontColorDrop.setBounds(rjX, yRow10, dWidth, height);
            fontColorDrop.addFocusListener(new focusListen());
            entryPanel.add(fontColorDrop);
            //the eleventh row (label)
            JLabel fontSizeLabel = new JLabel("Select Font Size:");
            fontSizeLabel.setBounds(ljX, yRow11, mWidth, height);
            entryPanel.add(fontSizeLabel);
            //the final row (entry)
            fontSizeText = new JTextField("12", 2);
            fontSizeText.setBounds(ljX, yRow12, tWidth, height);
            fontSizeText.addFocusListener(new focusListen());
            entryPanel.add(fontSizeText);
            //display panel code
            //use test parameters
            //these will later be retrieved from the entries
            drawCanvas.setParams("Hello", "roundRect", Color.red,
                                100, 100, "Serif", Color.black, 12);
            //set the applet to visible
            //set to visible and display
            entire.setSize(800, 600);
            entire.setVisible(true);
        }   //end the init method
        //declare an inner class to handle events
        private class focusListen implements FocusListener
            //supply the implementation of the actionPerformed method
            //pass an event variable as the argument
            public void focusLost(FocusEvent e)
            { JOptionPane.showMessageDialog(null, "Focus lost."); } 
            //declare an empty focus gained function
            public void focusGained(FocusEvent e) {}      
        }   //end testListen class
    }   //end DemoShape class

    Sorry for glossing over your code sample, particularly as it looks like one of the best I've seen so far on the forums, but I'm pretty sure the answer you are looking for is as follows:
    Java doesn't render a component until paint() is called so until then you are not going to have any size settings because the jvm simply doesn't know how big the visual component is. This makes sense when you think about what the jvm is doing. The layout manager controls the display of the components depending on the settings it is supplied. So until it knows how many components you want, where, what kind of spacing, etc, etc, etc, how can the size be determined.
    The true cycle of events is therefore:
    create an instance of DisplayCanvas,
    add it to your container,
    make the container visible (which renders the component),
    get the size of the DisplayCanvas instance.
    You are being hampered because your desired chain of events is:
    create an instance of DisplayCanvas,
    get the size of the DisplayCanvas instance,
    add it to your container,
    make the container visible.
    This state of affairs is highly annoying and then leads to the next question "what do we do about that?". There is a cunning trick which is to get the jvm to render the component to an off-screen image, thus calculating the dimensions of the component so that you can do precisely the kind of enquiry on the object that you have been looking for. It should be noted that this may not be the visual size for all the reasons given above, but it is the "preferred size" for the component. Check the Swing tutorials and have a look at the section on Layout Managers for a run down on what that means.
    Anyway, we can use this handy code sample to determine the preferred size for your component. Notice the call to "paint()" (normally you would never make a direct call to paint() in swing) and the "g.dispose()" to free resources:
    package com.coda.swing.desktool.gui;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    public class PaintUtil
         public PaintUtil()
              super();
         public static Component paintBuffer(Component comp)
              Dimension size = comp.getPreferredSize();
              comp.setSize(size);
              BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2 = img.createGraphics();
              comp.paint(g2);
              g2.dispose();
              return comp;
    }Before you make a call to getWidth() or getHeight() put in a call to "PaintUtil.paintBuffer(this);" and see what happens.
    By the way, I can't claim credit for this code ... and I really wish I could remember where I got it from myself so I can thank them :)

  • Image width and height

    I cannot get DW8 to insert the width and height automatically
    whern inserting an imge. Can anyone help me with it. TIA

    I have just discovered that if you do the insertion when Code
    view and
    Design view are 'in synch', i.e., neither the Property
    inspector nor the CSS
    panel have a "Refresh" button, the width and height will be
    inserted in Code
    view.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.dreamweavermx-templates.com
    - Template Triage!
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    http://www.macromedia.com/support/search/
    - Macromedia (MM) Technotes
    ==================
    "intedeco" <[email protected]> wrote in
    message
    news:ebdb54$5uq$[email protected]..
    > Thanks ACE for the info. I am using the technique you
    mentioned.
    > However, I
    > did not have this problem in DWMX. Also, according to
    Macromedia 'HELP'
    > it is
    > inderted automatically. Thios is what is says:
    >
    >
    W and H are the width and height of the image, in pixels.
    Dreamweaver
    > automatically updates these text boxes with the image?s
    original
    > dimensions
    > when you insert an image in a page.
    >
    > Hopefully, next update will fix this!
    >

  • Losing width and height information of Image???

    Hi,
    I am losing the width and height information between converting an image to byte[] and then back to Image
    public void testImageToBufferAndBack(Image takenImage){
    BufferedImage bufimage = this.ImageToBufferedImage(takenImage);
    System.out.println("buffimage"+bufimage.getWidth()+" "+bufimage.getHeight(null)); //works fine
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
    ImageIO.write(bufimage, "jpeg", stream);
    catch (IOException ex) {
    byte[] bytes = stream.toByteArray();
    byte[] pictureBytes = bytes;
    Image testImage = Toolkit.getDefaultToolkit().createImage(pictureBytes);;
    System.out.println("tttttttteeeeeeeessssssttt "+testImage.getWidth(null)+" "+testImage.getHeight(null));
    Output:
    buffimage320 240
    tttttttteeeeeeeessssssttt -1 -1
    Could someone point me out my mistake please??

    Your mistake is not realizing that java.awt.Image loads images asynchronously. When Toolkit's
    createImage method returns an Image, that image contains no pixel data -- as you've seen above, it doesn't
    even know the size of the image! I knew this was the behaviour of the createImage method that took a URL,
    but was surprised here that this is also the case with the version that takes a byte[], but undoubtably, that is
    what is happening here. The way to fix this is always the same: use a MediaTracker, as my demo below
    illustrates.
    A couple points:
    1. If you render your image in a custom component like this it will eventually appear:
    g.drawImage(image, x, y, this); //for exampleThat's because Component's default behaviour as an ImageObserver (the reason for the final this)
    is to continually repaint as more pixel data becomes available. This is not always the best solution -- what
    if you need to know the image's dimension sooner rather than later?
    2. ImageIcon can load an image for you, by using a MediaTracker behind the scenes:
    Image image = ...
    new ImageIcon(image);
    //now image is loaded...Just be aware that if you use its constructors that don't take Image, but for example URLs
    URL url = ...
    Image image = new ImageIcon(url).getImage();Behind the scenes it's first getting the Image with Toolkit's getImage (not createImage). Toolkit's
    getImage caches the image, which may not be what you want if you are processing many images --
    why have the image loiter in memory if there is no advantage to that?
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    public class Example {
        public static void main(String[] args) throws IOException {
            String url = "http://today.java.net/jag/bio/JagHeadshot-small.jpg";
            BufferedImage original = ImageIO.read(new URL(url));
            displayDimensions("original buffered image", original);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(original, "jpeg", out);
            byte[] bytes = out.toByteArray();
            Image image = Toolkit.getDefaultToolkit().createImage(bytes);
            displayDimensions("created image", image);
            loadImage(image, new Label()); //any component will do
            displayDimensions("loaded image", image);
            System.exit(0);
        //handy dandy utility method
        public static void loadImage(Image image, Component comp) throws IOException {
            MediaTracker mt = new MediaTracker(comp);
            mt.addImage(image, 0);
            try {
                mt.waitForID(0);
            } catch (InterruptedException e) {
                throw new RuntimeException("Unexpected", e);
            if (mt.isErrorID(0))
                throw new IOException("Error during image loading");
        static void displayDimensions(String msg, Image image) {
            System.out.println(msg + ", w=" + image.getWidth(null) + ", h=" + image.getHeight(null));
    }Output:
    original buffered image, w=235, h=240
    created image, w=-1, h=-1
    loaded image, w=235, h=240

Maybe you are looking for

  • ERROR WHILE PRODUCT GROUP CREATION

    Dear All, I am trying to creat the product Group but system is giving the following error. Message No.M3749 "Required parameters missing when calling up module". Please give your valuable input to overcome the issue. Thanks & Regards, Vijay Mankar +9

  • Having trouble getting my ipod to be recognized by my computer

    I can't seem to get my ipod touch to be recognized by my computer. I already have itunes installed because my brother also has an ipod touch. Whenever i connect mine though it recognizes my ipod as a camera. any help?

  • How do I import my itunes to my new computer from an external hard drive?

    So i have reciently bought a new laptop and want to transer all of my itunes on to my new computer. I have put all of my itunes onto an external hard drive but am unsure of how to put it on to my new computer. I have downloaded itunes on to my new co

  • Locked in text field

    I'm setting up a daily calendar using text fields for a person to enter their name in a certain time spot. Is there a way that once their name is in that spot on the calendar it is locked in so that no one else can delete or change it? Thanks for the

  • Report with step by step

    Hi any given report .fist how to satrt with them,plse give some example any small report with step by step..... that is urgently