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?
getsize(image_name) # print the size before compression/resizing print("[*] Size before compression:", get_size_format(image_size)) if new_size_ratio < 1.0: # if resizing ratio is below 1.0, then multiply width & height with this ratio to reduce image size img = img. resize((int(img. size[0] * new_size_ratio), int(img.
Those who know a bit of python can install python and use pip install pillow in command prompt(terminal for Linux users) to install pillow fork. Assemble all the files in a folder and keep the file Compress.py in the same folder. Run the python file with python.
Resizing Images using Pillow (PIL) Pillow is one of the most popular options for performing basic image manipulation tasks such as cropping, resizing, or adding watermarks. Install the latest version of Pillow with pip . Pillow provides the resize() method, which takes a (width, height) tuple as an argument.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With