Not yet rated

Problem

You have images, some of which are portrait and others are landscape in a directory and you want to scale the images to fit in a grid layout so that the longest side is a specific size and the shortest size scales proportionally.

Solution

ColdFusion 8 introduced a several powerful image manipulation functions which we can use to solve this problem.

Detailed explanation

<!--- 
set the size in pixels for the longest side of the
thumbnail image 
--->
<cfset maxDimension = 100>

<!--- 
get all the images in a specific directory 
--->
<cfdirectory action="list"
    directory="#ExpandPath( 'images/gallery' )#"
    filter="*.jpg|*.jpeg|*.gif|*.png"
    name="list">

<!--- 
cfdirectory creates a query object which we can loop
through 
--->
<cfloop query="list">

    <!---
    Get the big image from the filesystem
    Note: The ImageNew() function can also use a full url
    --->
    <cfset myImage = ImageNew( list.directory & "/" &
list.name )>
       
    <!--- 
    create a thumbnail with the longest side scaled to
50px
    --->
    <cfif ImageGetWidth( myImage ) gt ImageGetHeight( myImage
)>
        <!--- 
        the width is greater than the height so portrait
        --->
        <cfset ImageResize( myImage, maxDimension, "" )>
    <cfelse>
        <!--- 
        the height is greater than the width so landscape
        --->
        <cfset ImageResize( myImage, "", maxDimension )>
    </cfif>
   
    <!--- 
    display images in a simple grid 
    --->
    <div style="width:110px; height:110px; float:left;
border:1px solid black">
        <cfimage action="writetobrowser" source="#myImage#">
    </div>
   
</cfloop>

It is worth considering, that resizing images on the fly is quite server intensive, so if this is a page that will be viewed frequently then you should consider creating the thumbnail images in a separate script, saving them onto your filesystem. You can then simply link to the thumbnail image you created.

To save the thumbnail to the filesystem instead of writing to the browser, you should use:

<cfimage action="write"
   destination="#ExpandPath( 'images/gallery/thumb/' )##list.name#"
   source="#myImage#">

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes