Instantly share code, notes, and snippets.

Embed
What would you like to do?
using netpbm to resize jpegs and pngs of arbitrary size to fixed square, preserving ratio with transparency
#
# solution for resizing jpegs and pngs of arbitrary size down to a 72x72
# square, preserving source ratio, and filling non-square sides with
# transparency
#
# ahead of time, convert a transparent 72x72 png to blank-72.pam and save
# it with your code
#
# pngtopam -quiet -alphapam < blank-72.png > blank-72.pam
#
# it would be nice to do all of this with just pipes, without the need for
# any temporary files, but whatever
#
when png
cat png | \
pngtopam -quiet -alphapam > a.pam
when jpeg
# hack to add an alpha channel to a jpeg, needed later
cat jpeg | \
jpegtopnm -quiet | \
pnmtopng -quiet | \
pngtopam -quiet -alphapam > a.pam
# scale down image to max width/height of 72, but might not be square, and
# then overlay it on blank-72.pam
cat a.pam | \
pamscale -quiet -xyfit 72 72 | \
pamcomp -quiet -mixtransparency -align=center -valign=middle - blank-72.pam > b.pam
# extract color channels and then alpha channel, because pnmtopng stupidly
# will not figure this out on its own
cat b.pam | \
pamchannel -quiet 0 1 2 > c.pam
cat b.pam | \
pamchannel -quiet 3 > c-alpha.pam
# convert to png with extracted alpha channel
pnmtopng -quiet -force -alpha=c-alpha.pam c.pam > resized-72x72.png
# clean up
rm -f {a,b,c,c-alpha}.pam
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment