In Python 3.x, I am using PIL to resize images, I know that we can reduce the height or width by subtraction or division by pixels. But, is it possible to resize an image to a desired size, say 200kb and remain its proportions? Assuming the image(s) is larger but the size is unknown.
相关问题
- Views base64 encoded blob in HTML with PHP
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
I am still learning Python, so there may be better ways, but here is a function that saves a PIL/Pillow image as a JPEG and allows you to specify a maximum size.
It uses a binary search to minimise the amount of work needed and it encodes into
BytesIO
memory buffer to save writing images to disk. If anyone has any suggestions for improvements, please let me know!If I run that as is, with target size of 100,000 bytes, I get:
If I change the target size to 50,000 bytes, I get:
Keywords: Python, PIL, Pillow, JPEG, quality, quality setting, max size, maximum size, image, image processing, binary search.