12

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?

smishra
  • 121
  • 1
  • 1
  • 4

2 Answers2

6

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)
Joe Web
  • 558
  • 5
  • 11
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.

milad_vayani
  • 398
  • 1
  • 4
  • 14