How do I scale a rectangle image while retaining its border thickness?

I want to create a programmatically scalable image like this: scales to .

Both have a one pixel border. If I scaled from the first to the second in Paint.NET, there would be a two pixel horizontal border, but I want it to keep it single-pixel.

You need to slice the image up in 9 parts. Four corners, four sides and the inner content.

In this image, you can see how each different slice can be resized to produce the result you desire. Do not scale corners, leave them be as they are. Then you need to scale the top and bottom side along x-axis, but not in y. And then left and right sides you need to scale in y axis, but not in x. Then obviously you need to scale the inner slice along both axis.

This can be done in multiple ways. I'm most familiar with OpenGL, so I'd just define the texture coordinates for the 9 different quads' vertices. You could also slice the image up in photoshop and use different parts of it as different textures (which is very slow, to be noted).

If your blocks really are as simple as a fill colour with a 1-pixel outline, you could just generate each image from scratch as you need it.

Here's a bash script using ImageMagick's convert program:

#!/bin/bash
declare -i width
declare -i height
width=$1 height=$2

convert \
-size "$width x$height" \
canvas:#ffd \
-fill none \
-stroke red \
-strokewidth 1 \
-draw "rectangle 0,0 expr $width - 1,expr$height - 1" \
block.png


Running the script with arguments 50 50 produces , while 50 25 makes and 100 10 .

You can of course do this with any other graphical toolkit if you want the images at run-time.