Calculating Image Dimensions

Yesterday I needed to get the dimensions of an uploaded image. I was just about to open up the Java API docs when I found this post over on Eddie Awad's Blog. So I know this is nothing new, but here is the method I wrote for my service. Note I'm passing in an ImageBean component and calling it's setWidth and setHeight methods once I have the dimensions.

<cffunction name="getDimensions" ... >
   <cfargument name="ImageBean" ... />

   <cfset var width = 0 />
   <cfset var height = 0 />
   <cfset var toolkit = "" />
   <cfset var image = "" />

   <cftry>
      <cfset toolkit = CreateObject("java","java.awt.Toolkit") />
      <cfset image = CreateObject("java","java.awt.Image") />
      <cfset image = toolkit.getDefaultToolkit().getImage(arguments.ImageBean.getFilePath()) />

      <cfset width = image.getWidth() />
      <cfset height = image.getHeight() />
      <cfset image.flush() />

      <cfcatch type="any">
         <cfset width = 0 />
         <cfset height = 0 />
      </cfcatch>         
   </cftry>

   <cfset arguments.ImageBean.setWidth(width) />
   <cfset arguments.ImageBean.setHeight(height) />
         
</cffunction>

Comments
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.