Reputation: 51
I'm trying to write a python script that takes in standard 24-bit pngs and converts them to 8-bit pngs for better compression. It looks like pypng can do this but I can't quite figure out how to use it. Image manipulation is a new area for me so this may seem silly. I have this currently:
r=png.Reader(<myfile>)
test = r.asRGBA8()
This gives me tuples in return (the layers of the image I believe). However I can't seem to write or save this back to an image. What am I missing? Here's a test image
Upvotes: 2
Views: 7431
Reputation: 207455
Original Answer
I think this does what you ask:
from PIL import Image
# Load image
im = Image.open('logo.png')
# Convert to palette mode and save
im.convert('P').save('result.png')
Updated Answer
I can't find a way to get PIL to make a sensible palette image as a result, but can do it a couple of other ways...
Either with wand
like this:
#!/usr/bin/env python3
from wand.image import Image
with Image(filename='logo.png') as img:
img.quantize(number_colors=256, colorspace_type='lab', treedepth=0, dither=False, measure_error=False)
img.save(filename='result.png')
Or, by shelling out to ImageMagick at the command-line and doing:
magick logo.png -colors 255 png8:logo8.png # use "convert" in place of "magick" if using v6
Newest Answer
Ok, I found a way to get PIL/Pillow to do a better job, and as expected, it makes use of libimagequant
which is not normally built into Pillow (at least on macOS where I am). The code looks like this:
#!/usr/bin/env python3
from PIL import Image
# Load image
im = Image.open('logo.png')
# Convert to palette mode and save. Method 3 is "libimagequant"
im.quantize(colors=256, method=3).save('result.png')
The steps, on macOS to build PIL/Pillow with libimagequant
are as follows - they will differ on other platforms but you should be able to get the general idea and adapt:
pip uninstall pillow # remove existing package
brew install libimagequant
brew install zlib
export PKG_CONFIG_PATH="/usr/local/opt/zlib/lib/pkgconfig"
pip install --upgrade Pillow --global-option="build_ext" --global-option="--enable-imagequant" --global-option="--enable-zlib"
Keywords: Python, image processing, PIL/Pillow, libimagequant, macOS, quantise, quantize.
Upvotes: 5