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

Similar Messages

  • Insert into .. sql return incorrect value for 2 columns,sometime no value

    Hello,
    Oracle 10.2.0.3 , sol 10. (recently upgraded from oracle9i & sol8)
    sql query is used to populate a table. sometimes it is populating same values for all the records in 2 columns. Sometimes not populating or partially populating 1 other column. other times its running fine.
    SQL is not changed at all. When run again , it populates correctly.
    any help is highly appreciatied.
    --pooja                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    no ORA errors while execution. Its completing successfully.
    and its an intermittent issue. when the SQL is run manually its gives perfect results. Rerunnign the entire process is also fine. Conclusivly, data & SQL has no problem.
    its an insert into table <SQL>
    SQL contains left outer join.
    example:
    Expected output:
    1 john texas
    2 smith MA
    3 rob michigan
    Actual Output
    1 john texas
    2 smith texas
    3 rob texas

  • How to set the width and height of the displayed image in a button

    How can I please specify the size of the image that I display in a button which I create dynamically.
                HtmlCommandButton button = new HtmlCommandButton();
                button.setImage(image.getUrl());Thanks in advance
    Message was edited by:
    WebService

    Follow some CSS tutorials to learn more about it.
    Here is a page with some links: http://www.google.com/search?q=css+tutorial
    Then you're doing or interpreting something wrong. The methods are actually there. I can play with them in my playground and they are also described in the the HtmlCommandButton API: http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/component/html/HtmlCommandButton.html

  • [JS] Page item (rectangle frame) width and height

    Following is my attempt at writing a function for width and height. It appears to work on rotated and sheared objects. Can anyone tell me if I'm on the right track?
    >function WidthAndHeight(myRectangle) // Returns an array [width,height]
    ]var myRectangleTopLeft = myRectangle.resolve(AnchorPoint.topLeftAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    var myRectangleTopRight = myRectangle.resolve(AnchorPoint.topRightAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    var myRectangleBottomLeft = myRectangle.resolve(AnchorPoint.bottomLeftAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    ]var d1x = (myRectangleTopRight[0][0] - myRectangleTopLeft[0][0]);
    var d1y = (myRectangleTopRight[0][1] - myRectangleTopLeft[0][1]);
    var myWidth = hypotenuse(d1x,d1y);
    var d2x = (myRectangleTopLeft[0][0] - myRectangleBottomLeft[0][0]);
    var d2y = (myRectangleTopLeft[0][1] - myRectangleBottomLeft[0][1]);
    var myHeight = hypotenuse(d2x,d2y);
    ]return [myWidth,myHeight];
    ]function hypotenuse(d1,d2)
    ]]return Math.sqrt ( Math.pow(d1,2) + Math.pow(d2,2) );

    Dave, you are absolutely right (no surprise here) about always returning points. I'm not sure, but I think this may actually be an InDesign bug. At the end of the 'resolve' method the 'true' value is meant to indicate 'use ruler units', I believe. Having read the documentation, however, it does seem like certain transformation coordinate spaces functions only work in points.
    To make this a more complete function, I've updated it to include a conversion to the current ruler units. I'm using the UnitValue object, and perhaps I'm misunderstanding something, but I cannot easily convert to a new UnitValue using the ruler measurements enumerations (it requires a string value to represent the target units). So I've had to include a switch function to get from the enumeration to the string value. Also, the UnitValue object does not seem to work with agates, and I haven't gone so far as to write my own conversion function for that, so the function has to exit with an alert if the user has agates as their ruler units.
    If anyone can offer a more elegant way of dealing with this, it would be great. Or even better, some insight into why the resolve method does not seem to honour the ruler units. This _is_ getting a bit over-the-top for a simple width and height function. Maybe Adobe will consider just adding the property to the page item and putting us all (well, certainly me, anyway) out of our misery (I've put in a feature request).
    > function WidthAndHeight(myRectangle) // Returns an array [width,height]
    ]] var myRectangleTopLeft = myRectangle.resolve(AnchorPoint.topLeftAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    var myRectangleTopRight = myRectangle.resolve(AnchorPoint.topRightAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    var myRectangleBottomLeft = myRectangle.resolve(AnchorPoint.bottomLeftAnchor, CoordinateSpaces.pasteboardCoordinates, true);
    ]] var d1x = (myRectangleTopRight[0][0] - myRectangleTopLeft[0][0]);
    var d1y = (myRectangleTopRight[0][1] - myRectangleTopLeft[0][1]);
    var myWidth = hypotenuse(d1x,d1y);
    var d2x = (myRectangleTopLeft[0][0] - myRectangleBottomLeft[0][0]);
    var d2y = (myRectangleTopLeft[0][1] - myRectangleBottomLeft[0][1]);
    var myHeight = hypotenuse(d2x,d2y);
    ]] var myHorizontalUnits = unitsEnumToString(app.documents[0].viewPreferences.horizontalMeasurementUnits);
    var myVerticalUnits = unitsEnumToString(app.documents[0].viewPreferences.verticalMeasurementUnits);
    ]] myWidth = new UnitValue(myWidth,"points");
    myHeight = new UnitValue(myHeight,"points");
    ]] myWidth = myWidth.as(myHorizontalUnits);
    myHeight = myHeight.as(myVerticalUnits);
    ]] return [myWidth,myHeight];
    ]] function hypotenuse(d1,d2)
    ]]]] return Math.sqrt ( Math.pow(d1,2) + Math.pow(d2,2) );
    ]] function unitsEnumToString(myUnitsEnum)
    ]]]] switch(myUnitsEnum)
    ]]]]]] case 2054188905 :
    ]]]]]]] return "points";
    ]]]]]] case 2054187363 :
    ]]]]]]] return "picas";
    ]]]]]] case 2053729891 :
    ]]]]]]] return "inches";
    ]]]]]] case 2053729892 :
    ]]]]]]] return "inches decimal";
    ]]]]]] case 2053991795 :
    ]]]]]]] return "millimeters";
    ]]]]]] case 2053336435 :
    ]]]]]]] return "centimeters";
    ]]]]]] case 2053335395 :
    ]]]]]]] return "ciceros";
    ]]]]]] default :
    ]]]]]]] alert("Cannot convert to the current ruler units. Sorry.");
    exit();

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

  • SWFLoader.content: stage width and height, can i override to return proper results  ?

    Hiya.
    I'm loading with SWFLoader games that where written using stage functions to get the width and height of the stage and to draw the game and calculate game movements accordinly. When I load a game using SWFLoader, the stage size changes from the stage size of the flash application that i loaded with SWFLoader to the stage size of my entire flex application with breaks the loaded flash application.
    is there a way to override the stage related functions in the loaded flash application in order for them to return the proper value ?
    if my flash application is width=50px height=50px and it's located at my flex stage at x=20px width=20px,
    then the width and height of the stage of the flash application will return 70px.
    is there a way to resolve that ?

    If an app has dependencies on stage size, it will not behave well as a
    sub-app.

  • How to set a minimum width and height for a stage or scene?

    Hello,
    Does anyone how to set a minimum width and height for a stage or scene?
    I tried listening for width/height property value changes and then adjust the width/height if necessary, but that causes unpleasant flickering of the window.
    In JavaFX 2.1 beta SDK for Mac OS, the Stage class has setMinWidth() and setMinHeight() functions which work very well.
    I'm wondering what's the equivalent way to do that when using the FX SDK for Windows.
    Any help is appreciated!
    Thanks.

    I was wondering how to enforce a minimum stage size with JavaFX 2.0.3.The same flickering way you are currently doing it. See: http://javafx-jira.kenai.com/browse/RT-15200 "Need a way to set the minimum size of a window"

  • [svn] 4793: Fix bug SDK-17734 Path with width and height set different than path data has incorrect bounds

    Revision: 4793
    Author: [email protected]
    Date: 2009-02-02 11:20:06 -0800 (Mon, 02 Feb 2009)
    Log Message:
    Fix bug SDK-17734 Path with width and height set different than path data has incorrect bounds
    Fix: When calculating the bounds position we should take into account the implicit scaling factor actualSize/naturalSize. Also did some refactoring, getting rid of the protected method calculateTopLeft.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-17734
    Reviewer: Ryan
    tests: mustella gumbo/layout/GraphicElement
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-17734
    http://bugs.adobe.com/jira/browse/SDK-17734
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Ellipse.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/Path.as
    flex/sdk/trunk/frameworks/projects/flex4/src/mx/graphics/graphicsClasses/GraphicElement.a s

    Thank you so much for replying.
    Yes I have removed and reinstalled WMP.
    I had good results with the PD6 application installed on the default path onto the C: drive with the one exception that if the application was launched by accident and the user data path was not available, the PD6 application would blow away my custom user path registry settings. Now that I know what they are I have made a .reg file to repair my registry to my desired user data paths.
    Installing the application on the removable drive appeared to help prevent me from launching the application by accident and overwriting my registry with default user paths.
    So which is the less of the two evils?
    If the application directory is not available, windows media player still tries to launch the .msi for installing PD6.
    If I install the application to the C: drive but the user data to the removable drive, launching the PD6 application without the user data drive will still corrupt my registry settings for a user data path.
    Both these issues seem like a logical (if not easy) fix that should be done in the PD6 application and installation package. I mean really, cannot anyone tell me why windows media player is checking the PD6 application directory? Why in PD4 did we have an option control for setting the user data path from the PD4 application? Why is this option not in the PD6 application, just the installer?
    I am given a choice during installation to move the user data to another non default location. Why else would this be provided if not to accommodate my kind of request to store the user data into an alternate location other than “My Document”. Certainly Palm is not trying to force the users on how to protect and store their personal data?
    Post relates to: Centro (Verizon)

  • Perspective 3D width and height (stage relative values) in Actionscript

    Hello!
    I have a small square movieclip in Stage, 100x100 width and height.
    I translated it 90º in Y axis. Then, it looks like almost a vertical line.
    I want to know the "Perspective 3D width" and "Perspective 3D height" values (something like 24x120 as the rotated square now looks like almost a vertical line).
    These values are shown in the movieclip properties, in "3D position and view".
    I put an image showing where the values appear. Does anyone know how I access the values via Actionscript?
    Thank you!

    Hello!
    Thanks for the feedback.
    After your answer, I searched for an hour to find the relation between matrix3D, transform, and the width and height properties. But I couldn't find the answer in there (I already had tried to search there before posting here).
    Maybe the answer can be there too, but "por casualidad" now I just found the solution using this piece of code:
    myMc.getBounds(root).height;
    myMc.getBounds(root).width;
    It solved the problem after 3 hours trying to find the solution! \o/
    Thanks for your attention!

  • How do I save the width and height of a photo for repeated use?

    How do I save the width and height of a picture for repeated use, rather than having to enter it each time in the 'new file' box?
    Thanks,  Ed Jackson.

    It could be that I'm older and have forgotten. I'm now 73 and will admit I have forgotten many things over the years. I have been using Photoshop since Photoshop version 3.  And can not really recall which features or changes were made in ever version of Photoshop I have installed.  Adobe has added many features over the years. The number of bugs introduce has also greatly increased after CS3.  "New Doc Sizes.psp"  in your user id preferences is edited using the two buttons in the new document dialog.
    As for guide lines in new documents Photoshop CS6 or CC seem to add some for video file presets with guide lines.  I do not know how to edit or add guide line to new doc presets. Guide line actions are easy to create. I have also seem some guideline in new documents when I did not expect any perhaps a new bug. Photoshop like most software has bugs. If you do not see Adobe new presets perhaps you copied an old  "New Doc Sizes.psp"  over Adobe's newer default file or Adobe migrared you presets and wand wiped their presets out. There are bugs. Close Photoshop down and rename your current  "New Doc Sizes.psp"  in you user id Photoshop cc preferences folder and start Photoshop it will add a dedault  "New Doc Sizes.psp"  file see if you see Adobe new presets in the new doc pull down when you select video and film...

  • Change the width and height of Landscape Layout for a report in 10G

    Hi,
    I'm new to reports and when i built the report in report builder 10g, the layout orientation was 'Landscape', hence I assumed that it'll be a landscape layout.
    However, the width and height fields of the main section are 11 and 20 respectively. However, the height should ideally be 8.5. When i try to change it I get the following error message :
    Layout canvas must remain large enough to fit layout objects.
    Could you please tell me how to change the height of this landscape layout to 8.5 from 20.
    The report has several main frames within a repeating frame, since the same report has to run multiple times.
    Is it possible to have a repeating page across pages (crossing the horizontal margin) and hence have some of the main frames move down to the next page. I'm trying to do this to then be able to reduce the height of the main section of the report to 8.5. Its not working though because I'm getting the following error :
    REP 1814 : Report cannot be formatted. Object "vertically" can never fit R_Main (the name of the repeating frame enclosing all objects)
    Thanks,
    Priyanka

    To reduce the Hieght, first make the layout design fit into the new value..

  • Please help me :How to set the width and height for my View page "test.htm"

    Hi,
        I have controller class. When i call the view[test.htm]from this controller class ,i am getting the view with output tableview..it is fine.
    My requirement:
                 the output view window is showing full browser window. I want the view output like showModeldialog. I want to set the width and height for the output view window. How is possible?
                 or
    i want to call the test.view in the window.showModelDialog..
    Please help me .. Urgent requirement.

    Yes you can set the width & Height of the view as follows..
    <div style="width:580px; height:750px; margin-top:15px; overflow:auto;">
    <htmb:form......>
    </htmlb:form>
    </div>
    <i>*Reward each useful answer</i>
    Raja T

  • W3c valid site, initially no error reported by developer toolbar. But upon right click (giving the validation menue), the the toolbar reports two errors: width and height. Despite the fact that every page is validated! On the forum for the toolbar, this i

    w3c valid site, initially no error reported by developer toolbar. But upon right click (giving the validation menue), the the toolbar reports two errors: width and height. Despite the fact that every page is validated! On the forum for the toolbar, this is said to be a Browser error. So, how can this be fixed? I'm using FF 3.6.6
    == This happened ==
    Every time Firefox opened
    == after update from 3.5?

    Hi Sara,
    Can you give us the URL of the page you're having problems with and of the forum thread you mentioned?
    Thanks!

  • 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 :)

  • How to calculate actual selection or group width and height with clipping

    If a group has clipping paths then the height and visible bounds will include the dimensions of all paths selected including the clipped or hidden paths.
    However, the width and height shown on the width and height of the AI detail boxes for the selection shows just the visible dimensions.
    I want to retrieve the same values that is shown on the screen when a group is selected.
    It is somewhat counterintuitive that the "visiblebounds" property does not show just what is visible.
    I'm scaling the visible content of a selection to fit within another path but I need to be able to calculate the dimensions of the only what is visible after clipping.
    What do you have to do with scripting to get these values? Go through all of the path items in a group recursively and save the min and max values of any visiblebounds for clipping paths? Any better alternatives that I don't see?
    Thanks for any help!

    I ended up using the visible bounds for both scale and position as I also discovered that attempting to position a group with the position method would also result in missing the mark. The top and left (x,y) bounds I calculated without the clipped dimensions needed to be used to offset the actual position where I wanted the visible paths to be displayed.
    The functions I used ended up looking like so:
    function GetPoints(dblInch)
         var dpi = 72;
         return dblInch * dpi;
    function getRealVisibleBounds(grp) {
         var outerBounds = [];
         for(var i = grp.pageItems.length - 1; i >= 0;i--)  {
              var bounds = [];
              if(grp.pageItems[i].typename == 'GroupItem') {
                   bounds =  getRealVisibleBounds(grp.pageItems[i]);
              else if((grp.pageItems[i].typename == 'PathItem' || grp.pageItems[i].typename == 'CompoundPathItem')
                   && (grp.pageItems[i].clipping || !grp.clipped)) {
                   bounds = grp.pageItems[i].visibleBounds;
              if (bounds.length > 0) {
                   outerBounds = maxBounds(outerBounds,bounds);
         return (outerBounds.length == 0) ? null : outerBounds;
    function positionVisible(grp,x,y)
         var bounds = getRealVisibleBounds(grp);
         var newX = GetPoints(x) + (grp.left - bounds[0]);
         var newY = GetPoints(y) + (grp.top - bounds[1]);
         grp.position = [newX,newY];
    function maxBounds(ary1,ary2) {
         var res = [];
         if(ary1.length == 0)
              res = ary2;
         else if(ary2.length == 0)
              res = ary1;
         else {
              res[0] = Math.min(ary1[0],ary2[0]);
              res[1] = Math.max(ary1[1],ary2[1]);
              res[2] = Math.max(ary1[2],ary2[2]);
              res[3] = Math.min(ary1[3],ary2[3]);
         return res;
    and were called like so:
    var doc = app.activeDocument;
    if (doc.selection.length > 0) {
         var grpOriginal = null;
         if(doc.selection.length == 1 && doc.selection[0].typename == 'GroupItem') {
              grpOriginal = doc.selection[0];
         else {
              grpOriginal = doc.groupItems.add();
         doc.selection = null;
         if(grpOriginal.layer.name != 'approval') {
              grpOriginal.move(doc.layers['approval'],ElementPlacement.PLACEATEND);
         var artBounds = getRealVisibleBounds (grpOriginal);
         var artWidth = artBounds[2] - artBounds[0];
         var artHeight = artBounds[1] - artBounds[3];
         var imprintHeight = GetPoints(0.625);       // 0.625 is new height, hardcoded for demonstration
         var imprintRatio = imprintHeight / artHeight;
         var section = doc.layers['sectionLeft'];    // section where I placed the art
         var grpArt = grpOriginal.duplicate(section,ElementPlacement.PLACEATEND);
         grpArt.resize(100.0 * imprintRatio,100.0 * imprintRatio);
         grpArt.move(section,ElementPlacement.PLACEATBEGINNING);
         grpArt.selected = true;
         positionVisible(grpArt,0.0,16.75);          // x & y hardcoded for demonstration
    else {
         alert('artwork needs to be selected');
    I'm new at this so are there any better options to do these things?

Maybe you are looking for

  • Message when installing OS X Mavericks locked hard drive

    Message when installing OS X Mavericks locked hard drive,copule you help me how to solve

  • Says I don't have enough space

    I want to download Infinity blade onto my iPhone while it's 99 cents and I cleared off my phone to where it says I have 1.0 gb free in the about menu. When I go to download infinity blade from the app store it says I dont have enough space. Infinity

  • Getting Exception in the select clause - Very Urgent

    Hi,     I have given the below statement but it is showing the exception.   SELECT *          FROM (lv_tab_name)          INTO CORRESPONDING FIELDS OF TABLE <fs_1>. If I execute the above select statement it is showing the below exception. Exception

  • CIF R3 material as Resource into APO

    Hi  Experts,    We have a requirement to CIF R3 material (belonging to a specific material group) in our case its packing material group (Vessel) as a Transportation Resouce in APO. We need these Products as a transportation resource in TP/VS. Regard

  • Finding/Deleting Synced Photos on Computer

    The community responses have not helped me resolve my deleting/ Finding my synced photos on my computer.  Please advise me as to where and how to locate tab for photos at iTunes (not sure what page it is on)  and any other pertinent instructions as t