Cropping to the center of an image

This week a user sent in what I thought was a rather simple request. He needed to find the center of an image. That’s pretty trivial math, so I fired back with the following:

<cfset image = "/Users/ray/Pictures/star-wars-stormtroopers-breakfast-cereal.jpg"> <cfset myImg = imageNew(image)> <cfset centerX = myimg.width/2> <cfset centerY = myimg.height/2>

Basically, your center is the point defined at half your width and half your height. However, I misunderstood his initial request. He wanted to take an image and crop it to a smaller size. But he wanted the crop to "center" around, well, the center. Let me explain with an example that demonstrates how just finding the center isn't enough. We will begin with our source image - which is not mine and I cannot find the credit.

Pretty snazzy, right? Now let's look at code that finds the center, and then crops at that point:

<cfset image = "/Users/ray/Pictures/star-wars-stormtroopers-breakfast-cereal.jpg"> <cfset myImg = imageNew(image)> <cfimage action="writeToBrowser" source="#myimg#"> <p/> <cfset centerX = myimg.width/2> <cfset centerY = myimg.height/2> <cfset imageCrop(myImg, centerX, centerY, 300, 200)> <cfimage action="writeToBrowser" source="#myImg#">

You can see my math in there (ok, it's division, and it's simple, but it's still math!) and the imageCrop that works with the center. However, this creates a crop that is displayed. It's from the lower right hand size of the image.

In order to correct this, we need to make a slight tweak to our code. Our math formula becomes:

x=width of image/2 - desiredwidth/2
y=height of image/2 - desiredheight/2

Here is the corrected code:

<cfset image = "/Users/ray/Pictures/star-wars-stormtroopers-breakfast-cereal.jpg"> <cfset myImg = imageNew(image)> <cfset imageCrop(myImg, (myimg.width/2) - (300/2), (myimg.height/2) - (200/2), 300, 200)> <cfimage action="writeToBrowser" source="#myImg#">

Which produces the following:

Better, right?

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.

Lafayette, LA