CFImage and PJPEG Images

I am currently porting a website from classic ASP into CF8 and one of the features that this site had was an automatic generation of thumbnails; so I used the wonders of CFImage (and some caching know-how to decrease the performance hit) to implement this, but then I ran into a very annoying limitation of CFImage, namely the inability to handle certain jpeg images.

For some images, whenever I attempted to read them from the file system using CFImage I would get the following error back:

Not a JPEG file: starts with 0x42 0x4d
An exception occurred while trying to read the image.

The weird thing was that I could see these images in the browser without a problem, and they even appeared as regular jpeg images. Then I remembered about progressive jpeg images, which is a particular type of JPGs but are designed to be displayed as if the image quality increases as it is being loaded.

However pjpeg is not one of the readable types by ColdFusion, so after some tinkering around, I found an interesting thing and I'm not sure if this is a bug in CFImage or not: Reading one of these images using will throw the error mentioned above, BUT if I created the image using imageNew() passing the binary contents of the image file then CF creates the image object without complain!

So I modified my thumbnail generation script so that whenever it finds one of these unreadable JPG images, it will then read the binary contents of the image, create a new image using the image data and then overwrite the source image with the newly created image, resulting in a normal JPEG image that can now be read without problems.

The relevant part of the script is this:

<cfif not isImageFile(expandPath(href))>
   <!--- image is not a valid image file (for CF), may be a pjpeg file,
      so we will attempt to convert it to a readable type --->

   <cffile action="readbinary" file="#expandPath(href)#" variable="strFile">
   <cfset oImage = imageNew(strFile)>         
   <cfimage action="write" destination="#expandPath(href)#" source="#oImage#" overwrite="yes">
</cfif>

href is the location of the image in the site. Hopefully someone will find this useful.

Comments
Aaron Longnion's Gravatar Oscar! You're my hero! I was pulling my hair out trying to figure out how this could be happening... my issue was with GIF images implicitly converted to JPG during cffile UPLOAD, but your code worked for me, too. Thank you!
# Posted By Aaron Longnion | 2/20/08 4:31 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner