Compress PNG image in Python using PIL
Asked Answered
G

2

14

I have a python script recorded with Selenium Builder that takes the full browser screenshot of a webpage using the following:

fileName = "Screenshot1.png"
webDriverInstance.save_screenshot(fileName)

The file size is about 3.5 MB since it is a long, scrollable page and I need the full browser screenshot. I need a way to compress the saved screenshots, or save them as smaller file size PNG images so that I can attach and send several such screenshots in the same email using another Python script (with smtplib).

I tried this:

fileName = "Screenshot1.png"
foo = Image.open(fileName)
fileName2 = "C:\FullPath\CompressedImage.png"
foo.save(fileName2, "PNG", optimize = True)

However, this doesn't seem to be working. Both files, Screenshot1.png and CompressedImage.png are of the same size (about 3.5 MB).

I tried several options with the save method but none of them seem to work. I do not get any errors when I run the script, but there is no decrease in the file size either.

foo.save(fileName2, "PNG", optimize = True, compress_level = 9)
foo.save(fileName2, "PNG", optimize = True, quality = 20)

I am using Python 2.7. Any suggestions?

Gimbals answered 25/1, 2016 at 22:56 Comment(3)
Hi, please check #10607968Umbel
This worked. Thank you !Gimbals
Wait... what's the difference between the link and what you were already doing?Amorete
A
8

I see two options which you can both achieve using PIL library given for instance an RGB image.

1 – Reduce the image resolution (and therefore quality – you might not want that). Use the Image.thumbnail() or Image.resize() method provided by PIL.

2 – Reduce the color range of the image (the number of colors will affect file size accordingly). This is what many online converters will do.

img_path = "img.png"
img = Image.open(img_path)
img = img.convert("P", palette=Image.ADAPTIVE, colors=256)
img.save("comp.png", optimize=True)
Artefact answered 2/3, 2022 at 18:52 Comment(0)
D
0

The PNG format only supports lossless compression, for which the compression ratio is usually limited and not freely adjustable.

If I am right, there is a variable parameter that tells the compressor to spend more or less time finding a better compression scheme. But without a guarantee to succeed.

Danita answered 18/1, 2021 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.