I'd like to work directly with compressed JPEG images. I know that with PIL/Pillow I can compress an image when I save it, and then read back the compressed image - e.g.
from PIL import Image
im1 = Image.open(IMAGE_FILE)
IMAGE_10 = os.path.join('./images/dog10.jpeg')
im1.save(IMAGE_10,"JPEG", quality=10)
im10 = Image.open(IMAGE_10)
but, I'd like a way to do this without the extraneous write and read. Is there some Python package with a function that will take an image and quality number as inputs and return a jpeg version of that image with the given quality?
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.
JPEG is a lossy image compression method. It employs a transform coding method using the DCT (Discrete Cosine Transform). An image is a function of i and j (or conventionally x and y) in the spatial domain.
For in-memory file-like stuff, you can use StringIO
.
Take a look:
from io import StringIO # "import StringIO" directly in python2
from PIL import Image
im1 = Image.open(IMAGE_FILE)
# here, we create an empty string buffer
buffer = StringIO.StringIO()
im1.save(buffer, "JPEG", quality=10)
# ... do something else ...
# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
handle.write(buffer.contents())
If you check the photo-quality10.jpg
file, it should be the same image, but with 10% quality as the JPEG compression setting.
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