ColdFusion Image Processing - Shrinking an image, but not the canvas

After my presentation yesterday, someone in the audience asked an interesting question. He wanted to shrink an image, but keep the original size. So imagine taking a large image, shrinking down the visual part of it, but keeping the image at the same size with some form of background now. This is relatively easy to do. First we can read in our source image:

<cfset source = "presentations/webmaniacs/images_lecture/originals/insp_captkirk.png">

<!— read it —> <cfset myimage = imageRead(source)> </code>

Then we can shrink it:

<!--- shrink it ---> <cfset imageScaleToFit(myimage,250,250)>

Now let’s create a new canvas. This will be a blank image. I’m picking an arbitrary size here. You could have checked the original images size instead, but for this example, I’ll just use 400x400. Also note I intentionally picked a non-white background so I could see it working.

<!--- new canvas ---> <cfset img = imageNew("", 400, 400, "rgb", "##c0c0c0")>

Lastly, all you do is paste the shrunken image over the blank canvas we just made:

<!--- paste it in ---> <cfset imagePaste(img, myimage, 0,0)>

Here is the final result:

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments