In Python's PIL, how do I change the quality of an image?
11,268
Solution 1
If the picture format is JPEG, here's an example:
from PIL import Image
im = Image.open("C:\Users\Public\Pictures\Sample Pictures\Jellyfish.jpg")
im.save("C:\Users\Public\Pictures\Sample Pictures\Jellyfish_compressed.jpg", quality=10)
The references you need to be reading are:
- [The Image module][1], particularly the "save" function, which allows you to pass in options relevant for each image format.
- Each image format's options are in a different page, you can find it in the docs.
Solution 2
Solved.
I did....
im.save( blah, quality=5)
Solution 3
a) change the size: Image.resize(size, filter)
b) explicitly convert it to JPEG (if it is not) and set the desired quality. c) use a combination of a) and b)
Whatever you do, there is a trade-off between size and quality.
Author by
TIMEX
Updated on June 14, 2022Comments
-
TIMEX almost 2 years
I want to degrade the quality of the image to a few kilobytes. What's the best way to do this?
Thanks!
-
khachik over 13 years
quality
is for JPEG only, it is ignored for another formats. -
Asim Ihsan over 13 yearsPNG accepts an "optimize" flag. You need to check each individual image format's docs to determine what optimization flags you can use.
-
martineau over 13 yearsFWIW, the OP isn't big on reading the documentation -- he's got S.O.
-
Karl Knechtel over 13 years@martineau also FWIW, I find the PIL documentation fairly spotty. IMX, you can't really just hack around with
dir
/help
/doc
and get answers as often as you'd like. Also, for example replacingpng
withjpg
in Asymptote's link yields a 404. -
martineau over 13 years@Karl Knechtel: It may not be the greatest documentation, but the answer to this question is in it. For
im.save()
it says "Keyword options can be used to provide additional instructions to the writer. If a writer doesn't recognize an option, it is silently ignored. The available options are described later in this handbook". If you then look in the JPEG appendix it says "The save method supports the following options: quality - The image quality, on a scale from 1 (worst) to 95 (best). The default is 75. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage". -
martineau over 13 years@Karl Knechtel: Here's a link for the PNG appendix in the online manual.
-
vijay shanker over 9 years@asim ihsan compressing this way.. image looses orientation data .. and pic at times get saved inverted/flipped etc... how to keep the exif data?
-
Asim Ihsan over 9 years@vijayshanker I can confirm that using PIL in this way does not retain EXIF metadata. You can use another Python module like
pyexiv2
to manually copy over the EXIF after creating the new file. For more information see: stackoverflow.com/questions/17042602/…