Wednesday, August 31, 2011

ImageMagick - A Google CustomMap Maker's Best Friend

I'm working on developing a custom map using Google's Map API, and finding ImageMagick's convert command to be invaluable.

Developing a custom map means generating a potentially thousands of scaled and tiled images. convert almost makes this too easy to do.

Here's a few recipes I've used so far:

# Convert a PDF to a PNG at a resolution given by 'density'
convert.exe -density 7    base.pdf base_007.png  # [1]
convert.exe -density 100  base.pdf base_100.png  # [2]
convert.exe -density 800  base.pdf base_800.png  # [3]

In each of the above cases, I'm generating a .png from the high quality PDF file. By varying the density, I can control the resulting PNG file. In my case, [1] generates a 256 pixel wide image, while [3] generates a 28,800 pixel image.

# Slice an image into 256x256 tiles
convert -crop 256x256 map.png tiles/map.png

The above command may not look like much, but the result is a tiles directory filled with 256x256 images. The file name is map-N.png, which I'll no doubt write a script to convert to map-Tx-Ty.png, where Tx and Ty are the appropriate tile coordinates.

# Convert a rectangular image to a square one
convert.exe map.png -background "#CCCCCC" \
   -resize 256x256 -background "#CCCCCC" \
   -compose Copy -gravity center -extent 256x256 \
   map_square.png

In the Google Maps examples, the base map used is square. To make playing with those examples, I use the above convert command to pad my images with a gray background. The above incantation was inspired by this question.

Oh, and it's probably worth mentioning that all these commands work just fine at a cygwin prompt, which is where I've been executing them.

If you want to slice and dice images, you need to learn ImageMagick. Period.

No comments:

Post a Comment