Wednesday Contest Solution (pt. 1)

Since I had a whopping zero takers for my contest, I'm thinking it won't be a repeat event. Here's my solution for the first portion of the challenge:

<cfif NOT isDefined("attributes")>
  <cfset attributes = structNew() />
  <cfset structAppend(attributes, form, false) />
  <cfset structAppend(attributes, url, false) />
</cfif>
<cfparam name="attributes.width" default="100" />
<cfparam name="attributes.height" default="100" />
<cfparam name="attributes.backgroundColor" default="f7f7f7" />
<cfparam name="attributes.borderColor" default="cccccc" />
<cfparam name="attributes.textColor" default="990000" />
<cfparam name="attributes.text" default="Hello!" />

<cfset image = imageNew("", attributes.width - 2, attributes.height - 2, "rgb", attributes.backgroundColor) />
<cfset imageAddBorder(image, 1, attributes.borderColor) />

<cfset imageSetAntialiasing(image, "on") />
<cfset imageSetDrawingColor(image, attributes.textColor) />

<cfset graphics = imageGetBufferedImage(image).getGraphics() />

<cfset bounds = graphics.getFontMetrics().getStringBounds(attributes.text, graphics) />
<cfset imageDrawText(
  image,
  attributes.text,
  (attributes.width - bounds.getWidth()) / 2,
  (attributes.height + bounds.getHeight()) / 2
) />

<cfimage action="writeToBrowser"
  source="#image#" />

I'm withholding the extra credit solution until tomorrow, in case anyone wants to take a crack at it.

4 Responses to “Wednesday Contest Solution (pt. 1)”


  1. 1 Ben Nadel

    Sorry I missed this one (this week has been horribly busy at work). I might have some time to give it a go tonight (the extra credit)… let me see what I can make happen.

  2. 2 Ben Nadel

    I couldn't solve this problem without cheating :( I didn't know about this whole getFontMetrics() thing in the underlying buffered image. I would not have been able to figure out how to center the text.

    I guess I really need to learn up on my Java AWT before I can really tackle tricky image stuff.

  3. 3 Ben Nadel

    Sorry, I don't want to bombard you with comments, but I've had a few minutes to play around with the FontMetrics() stuff you have in your example - awesome stuff! Being able to grab the font bounding box is giving me some great ideas. Thanks.

  4. 4 barneyb

    Yeah, the underlying Java APIs are quite powerful. I'm just a little annoyed that accessing them, particularly regarding drawing text is so annoying. If you want another 15 minutes or so, the second part of the solution (the extra credit) will publish itself, and you can see how cumbersome it is.

Leave a Reply