Seabright Technology Header Image

Automatically trimming matplotlib images

matplotlib is a great mathematics and plotting package for Python. I’m using it to report on some benchmarking numbers but needed a way to automatically trim the extra whitespace before putting onto a web page. Here’s the ImageMagick command I ended up using:

convert input.png -bordercolor white -border 1x1 -trim +repage -alpha off +dither -colors 32 PNG8:output.png

To break it down:

  • -bordercolor white -border 1x1 – add a one pixel white border to make sure trim trims the right colour, and to remove a single pixel artifact in the top left.
  • -trim – trim the extra whitespace
  • +repage – recentre the image on the canvas
  • -alpha off – drop the alpha channel, if any
  • +dither -colors 32 – dither down to 32 colours
  • PNG8:output.png – write out to output.png in 256 colour mode.

The PNG8: is the secret sauce – for every other option I tried, ImageMagick would still write out a 32 bit colour file.

These together shrink 592 kB of images down to 144 kB.

Leave a Reply