ImageMagick Snippets[source]

xml
<glacius:metadata>
    <title>ImageMagick Snippets</title>
    <description>Collection of small ImageMagick scripts I can never remember</description>
    <category>Code snippets</category>
    <category>ImageMagick</category>
    <category>Programming</category>
    <category>Bash</category>
</glacius:metadata>
<h2>Make image square</h2>
<glacius:code lang="bash"><![CDATA[
# 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
]]></glacius:code>
<h2>Properly scale pixel art</h2>
<p>
    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.
</p>
<p>
    By setting the <a href="https://legacy.imagemagick.org/Usage/filter/#point"><code>-filter</code> 
    option to <code>point</code></a>, this will do no longer do fancy math to generate the new 
    color for each pixel.
</p>
<glacius:code lang="bash"><![CDATA[
magick input.png -filter point -resize x480 -strip output.png
]]></glacius:code>
<h3>Other options</h3>
<p>
    ImageMagick actually supports doing some pixel art-specific magnification
    with the <code>-magnify</code> 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.
</p>
<p>
    My input image was 12x30, so first I made it square using <code>-extent 30x30</code>
    and then performed the magnify/resize operations to get it to the desired 44x44.
</p>
<glacius:code lang="bash"><![CDATA[
magick input.png \
    -gravity center -background transparent -extent 30x30 \
    -filter point -magnify -resize 44x44 \
    output.png
]]></glacius:code>
<p>
    Keep in mind, however, that obviously it's never going to be perfect when scaling
    by factors that are not multiples of 2.
</p>