Skip to content

Instantly share code, notes, and snippets.

@jcs
Created June 4, 2016 16:25
Show Gist options
  • Save jcs/2cee124dfba2198be334c954b65a5855 to your computer and use it in GitHub Desktop.
Save jcs/2cee124dfba2198be334c954b65a5855 to your computer and use it in GitHub Desktop.
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