UDF: imageScaleThenFit

I wrote this UDF as a replacement for functionality built into ImageCR3. One of my clients is upgrading from CF7 to CF9 soon and as part of that upgrade we needed to replace ImageCR3 because it doesn't work (well?) on CF9.

One quirk about ImageCR3 is that, by default, when you do an image resize, it does a combination of a scale and resize. Say your original is 600px by 500px, and you tell ImageCR3 to resize it to 300x300, then it will first scale the image down proportionally so that it will fit within a 300x300 box without skewing, and then add whitespace (or whatever background color you provide) to fill in the rest so that the result is exactly 300x300.

Since I'm replacing that functionality, I had to duplicate it using the CF9 Image functions. It wasn't incredibly difficult, but I figured someone else might be looking for the same thing. I was going to post it on CFLib, but the CAPTCHA system is currently broken, so submissions are functionally disabled.

Here's my UDF:

function imageScaleThenFit(img, w, h, bg = "white"){
    var info = '';
    var cp = '';
    var x = 0;
    var y = 0;
    imageScaleToFit( img, w, h );
    info = imageInfo( img );
    if (info.width < w or info.height < h){
        cp = imageCopy( img, 0, 0, info.width, info.height );
        img = imageNew( "", w, h, "rgb", bg );
        x = fix((w - info.width) / 2);
        y = fix((h - info.height) / 2);
        imagePaste( img, cp, x, y );
    }
    return img;
}

Note that it returns the image. I'm not sure if an image variable is passed by value or by reference, so I returned the result just in case.

Published 2012-06-15 10:37 in 2 Responses ColdFusion

2 responses:

James E

James E

2012-06-18 @ 9:28 AM
This is excellent! Just what I was looking for!
James Moberg

James Moberg

2012-06-18 @ 9:58 AM
On some projects, I've use the getPixels() function of the imageUtils library to automatically identify the background color (so that background colors aren't always white.)
http://imageutils.riaforge.org/

bgColor = imageutils.GetPixel(img, 1, img.Height\2);
newImage = ImageNew("", "#x#.001", "#y#.001", "rgb", bgColor.hex);

Your comment:

Leave this field empty:




Playing Games to Save Kids Lives
+