ImageMagick Snippets @ r4

Contents hide

Make image square

bash
# crop image to fit within square
magick input.png -gravity center -thumbnail 400x400^ -background transparent -extent 400x400 -strip output.png

# scale image to fit within square
magick input.png -gravity center -thumbnail '400x400>' -background transparent -extent 400x400 -strip output.png

Properly scale pixel art

By default, resizing an image using ImageMagick will do some kind of intelligent interpolation to get the new color value of each pixel (i.e. antialiasing). Normally, this is what you want. For pixel art, however, you absolutely don't want that. If each "pixel" in the image maps to a 4x4 pixel on the screen, and you resize it by half, you would expect each new "pixel" to be a 2x2 pixel on the screen. Due to the default interpolation filters in ImageMagick, that doesn't happen, and you get "smudgy" pixels that bleed into each other instead of sharp pixels, like you would expect in pixel art.

By setting the -filter option to point, this will do no longer do fancy math to generate the new color for each pixel.

bash
magick input.png -filter point -resize x480 -strip output.png

Other options

ImageMagick actually supports doing some pixel art-specific magnification with the -magnify option (magnifies by 2x). In my particular case, I wanted to magnify by a factor that is not 2, so I ended up doing something like this, which ended up being a litle bit better than a straight resize.

My input image was 12x30, so first I made it square using -extent 30x30 and then performed the magnify/resize operations to get it to the desired 44x44.

bash
magick input.png \
    -gravity center -background transparent -extent 30x30 \
    -filter point -magnify -resize 44x44 \
    output.png

Keep in mind, however, that obviously it's never going to be perfect when scaling by factors that are not multiples of 2.