Friday, June 08, 2007

Finding Image Type for a file

This is a follow up on my previous post on URLConnection APIs
We will use this API to find out the image type of a given file. Here is the udf.

<cffunction name="getMimeType">
<cfargument name="filepath">

<cfset var urlConn = createObject("java", "")>
<cfset var fileobj = fileopen(filepath, "readbinary")>
<!--- just read the first 20 characters of the file as thats sufficient --->

<cfset var bytes = fileread(fileobj, 20)>
<cfset var istream = createObject("java", "").init(bytes)>
<cfset fileobj.close()>
<cfreturn urlConn.guessContentTypeFromStream(istream)>

<cffunction name="GetImageType">
<cfargument name="filepath">
<cfset var mimetype = getMimeType(filepath)>
<cfset var imagetype="">
<cfif not isDefined("mimetype")>
<cfthrow message="Not an Image file">
<cfswitch expression="#mimetype#">
<cfcase Value="image/gif">
<cfset imagetype="gif">
<cfcase Value="image/x-bitmap">
<cfset imagetype="bmp">
<cfcase Value="image/png">
<cfset imagetype="png">
<cfcase Value="image/jpeg">
<cfset imagetype="jpeg">
<cfcase Value="image/jpg">
<cfset imagetype="jpeg">
<cfthrow message="Not an Image file">
<cfreturn imagetype>

If I run the code below

<cfset filepath = "C:\temp\test.jpg">

It nicely prints out "jpeg".

You should note that I used the new File IO function added in ColdFusion 8 using which I can read as many no of bytes from the file as I want. No more reading the entire file into memory.

More extensive post on File IO functions coming next !

1 comment:

Tomas Fjetland said...

Thanks, very useful!