Converting images

ColdFusion makes it easy to convert images from one file format to another. Also, you can convert an image file to a binary object, BLOB data, or a Base64 string.

Converting an image file

The extension of the destination file determines the file format of the image. Therefore, to convert an image, simply change the filename extension in the destination file. The following example shows how to convert a JPEG file to a GIF file:

<cfimage source="../cfdocs/images/artgallery/jeff01.jpg" action="write" destination="jeff01.gif">

Similarly, you can use the ImageWrite function with the ImageNew function:

<cfset myImage=ImageNew("../cfdocs/images/artgallery/jeff01.jpg")> 
<cfset ImageWrite(myImage,"jeff01.gif")>

In both examples, the convert action is implied.

The write action does not create a ColdFusion image; it simply writes an image to a file. To convert an image and generate a ColdFusion image variable, use the convert action:

<cfimage source="../cfdocs/images/artgallery/jeff01.jpg" action="convert" 
    destination="jeff01.gif" name="myImage">

ColdFusion reads and writes most standard image formats. For more information, see Supported image file formats in the CFML Reference.

Converting an image to a Base64 string

To convert a ColdFusion image to a Base64 string, use the ImageWriteBase64 function. In the following example, the yes value determines that the output includes the headers required for display in HTML:

<!--- This example shows how convert a BMP file to a Base64 string. ---> 
<cfset ImageWriteBase64(myImage,"jeffBase64.txt","bmp","yes")>
Note: Microsoft Internet Explorer does not support Base64 strings.

Inserting an image as a BLOB in a database

Many databases store images as BLOB data. To insert a ColdFusion image into a BLOB column of a database, use the ImageGetBlob function within a cfquery statement, as the following example shows:

<!--- This example shows how to add a ColdFusion image to a BLOB column of a database. ---> 
<!--- Create a ColdFusion image from an existing JPEG file. ---> 
<cfimage source="aiden01.jpg" name="myImage"> 
<!--- Use the cfquery tag to insert the ColdFusion image as a BLOB in the database. ---> 
<cfquery name="InsertBlobImage" datasource="myBlobData"> 
INSERT into EMPLOYEES (FirstName,LastName,Photo) 
VALUES ("Aiden","Quinn",<cfqueryparam value="#ImageGetBlob(myImage)#" cfsqltype="cf_sql_blob">) 
</cfquery>