开发者

How to downsize, scale, and colour-reduce PNGs at the command line? (Linux, Makefile)

开发者 https://www.devze.com 2023-03-27 10:26 出处:网络
Fr开发者_运维技巧om within a Makefile I like to reduce the size of PNGs. I tried first ImageMagick, but while I could resize (down) the images and reduce their colours to 32 (or the depth to 5 bits),

Fr开发者_运维技巧om within a Makefile I like to reduce the size of PNGs.

I tried first ImageMagick, but while I could resize (down) the images and reduce their colours to 32 (or the depth to 5 bits), the actual file size was bigger than the original in most cases.

With GraphicsMagick the results are similar, sometimes slightly better, sometimes worse.

[gm] convert input.png -trim -resize 600 -depth 5 -quality 100 output.png

With the Gimp, the results are always perfect. After down-scaling the image and reducing the colours to 32, the resulting images are always much smaller than the originals. Unfortunately, using the Gimp from a Makefile is a little bit difficult and I don't know lisp, only Python.

Questions: - Is there a way to make ImageMagick or GraphicsMagick reduce the PNG size? - Is there an easy way of performing this transformations with the Gimp instead, preferable using Python? - Are there other free tools around to help with this task?


I answer my own question. In the Makefile one has to create and use a temporary Gimp directory, so that one uses the script from the version control system, not an arbitrary local copy. One should batch process image files, because Gimp is relatively slow in startup.

mkdir -p gimp/plug-ins
cp downsize.py gimp/plug-ins/
GIMP2_DIRECTORY=`pwd`/gimp gimp --no-interface \
    --batch '(python-fu-downsize RUN-NONINTERACTIVE 600 32 "origdir" "copydir")' \
    --batch '(gimp-quit 0)'

The script downsize.py is a normal Gimp Python script, which mainly contains something like:

def downsize(img_w, img_d, in_dir, out_dir):
    for fn in glob.glob(os.path.join(in_dir, "*.png")):
        img = pdb.gimp_file_load(fn, '1')
        if img.width > img_w:
            aspect = float(img.width)/float(img.height)
            h = int(float(img_w)/aspect)
            pdb.gimp_image_scale(img, img_w, h) 
            if img.base_type != RGB:
                pdb.gimp_convert_rgb(img)
            if img.base_type != INDEXED:
                pdb.gimp_convert_indexed(img, NO_DITHER, MAKE_PALETTE, img_d, False, True, "")
            new_path = os.path.join(out_dir, os.path.basename(fn))
            pdb.gimp_file_save(img, pdb.gimp_image_active_drawable(img), new_path, fn)

This code may not be correct, it's just the basic idea.


Try pngcrush: http://pmt.sourceforge.net/pngcrush/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号