I’m working on a Freecell solitaire card game for Android (here the page). A card game requires cards; but where can I take card images? Looking for them in Internet is not fun enough, much better to write a script to generate them!

We can use ImageMagick and a bash script to draw a deck of 52 cards. The idea is to use a simplified design good for smartphones’ small screens. We need to draw:

  1. A rectangular white background with rounded corners;
  2. The card symbol (A, 2, …, J, Q, K);
  3. The suit symbols (twice).

I found a public domain version of the suit symbols on Wikipedia, put in the public domain by Flanker. I just split it in four files, and then I exploited them in an ImageMagick command.

The command to use is convert. It not only converts an image, but also can create a new one. For example:

    convert -size 380x530 xc:transparent 

creates a transparent image with the specified size.

To draw a white rectangle we may add the –draw flag:

    -fill white -stroke black -strokewidth 2 -draw 'roundRectangle 2,2 376,526 20,20'
 

Then we may want to write the card name with -annotate:

    -pointsize 150 -fill $COL -stroke none -annotate +16+142 "A" 

–draw can help also with the suit symbols

-draw "image over 228,25 120,120 's1.png'" 
-draw "image over 50,200 280,280 's1.png'" 

If we want to save a bit of space we can reduce the number of colors

            +dither -colors 256 

Then we can save the file

            out/card-ace.png

Generated card

A small bash script may help us to generate 52 cards in the out subdirectory:

#!/bin/sh
cn=0
mkdir -p out
for s in '1' '2' '3' '4'
do
    case $s in
    "1")
        COL=Black
        ;;
    "2")
        COL=Black
        ;;
    "3")
        COL=Red
        ;;
    "4")
        COL=Red
        ;;
    esac
       
    for c in 'A' '2' '3' '4' '5' '6' '7' '8' '9' '10' 'J' 'Q' 'K'
    do
        convert -size 380x530 xc:transparent  \
            -fill white -stroke black -strokewidth 2 -draw 'roundRectangle 2,2 376,526 20,20'\
            -pointsize 150 -fill $COL -stroke none -annotate +16+142 "$c" \
            -draw "image over 228,25 120,120 's$s.png'" \
            -draw "image over 50,200 280,280 's$s.png'" \
            +dither -colors 256 \
            out/card-$cn.png
        ((cn=cn+1))
    done
done

The script is hosted on github: https://github.com/epman/cardsgen