Avg. Rating 5.0

Problem

You have a UI element that holds an image of a specific size that needs to be managed by the client but...uh oh...never trust the client to upload the correctly sized image.

Solution

This function will take whatever obnoxiously size images it receives and resizes and crops down to the target size while centering on the content

Detailed explanation

  After the client uploads a 4000x3000 image that should have been say... 200 x 300 this function checks the dimensions of the uploaded file and determines which axis (x or y) more greatly overshoots the intended image size. It then resizes the image down to the opposite axis (the shorter axis) so that it's dimensions just fit withing the targeted size. Going back to the larger axis... the function centers on that axis and trims off the ends so that the targeted image size is achieved. Interpolation is added as an argument to balance quality with performance.

If only one axis extends beyond its target the that axis is centered and trimmed.  

If neither of the images axis breach their intendid targets then the image is immediately returned.

Usage

<cfscript>

uploadedFile = ImageNew("C:\images\myimage.jpg");  resized =
smartResize(uploadedFile,142,142, "hamming");

  /*  Further manipulate or write to file/screen */



 </cfscript>



Function

        <cffunction name="smartResize" returntype="any" access="public" output="no">
<cfargument name="image" type="any" required="yes" hint="cfimage obj" />
<cfargument name="w" type="any" required="yes" hint="Final Image Width" />
<cfargument name="h" type="any" required="yes" hint="Final Image Height" />
<cfargument name="interpolation" type="string" required="no" default="mediumPerformance" />

<cfscript>

i = ImageNew(arguments.image); // update to pass by reference and not by value

if(i.width > w && i.height > h){
if(i.width > i.height){
imageScaleToFit(i,'',h,arguments.interpolation);
if(i.width > w){
imageCrop(i,round((i.width - w) / 2),0,w,h);
}
} else if(i.height > i.width) {
imageScaleToFit(i,w,'',arguments.interpolation);
if(i.height > h){
imageCrop(i,0,round((i.height - h) / 2),w,h);
}
} else {
imageScaleToFit(i,w,'',arguments.interpolation);
}
} else if (i.width > w && i.height < h) {
imageCrop(i,round((i.width - w) / 2),0,w,h);
} else if (i.width < w && i.height > h) {
imageCrop(i,0,round((i.height - h) / 2),w,h);
}

return i;

</cfscript>
</cffunction>
  

+
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