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.
Top answer 1 of 3
20
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.
2 of 3
12
Using BytesIO
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from io import BytesIO
def generate(self, image, format='jpeg'):
im = self.generate_image(image)
out = BytesIO()
im.save(out, format=format,quality=75)
out.seek(0)
return out
StringIO is missing in Python3.0, ref to : StringIO in python3
The Python Code
thepythoncode.com › article › compress-images-in-python
How to Compress Images in Python - The Python Code
However, in this tutorial, you will learn to reduce image file size in Python using the Pillow library. You're free to use the code for this tutorial. For instance, you can make an API around it to reduce image sizes in batches instead of using a third-party API that may cost you money. I made the code for this tutorial as flexible as possible. You can compress the image and resize it with a scaling factor or exact width and height.
DEV Community
dev.to › khatrivinay › compress-images-size-with-python-4ipj
Compress Images size with Python - DEV Community
August 27, 2022 - from turtle import width import PIL from PIL import Image #open the image with Image.open('original.jpg') as my_image: #new widht and height in px width = 400 height = 700 print("The original size of Image is: ", round(len(my_image.fp.read())/1024,2), "KB") #compressed the image my_image = my_image.resize((width,height),PIL.Image.NEAREST) #save the image my_image.save('compressedResized.jpg') #open the compressed image with Image.open('compressedResized.jpg') as compresed_image: print("The size of compressed image is: ", round(len(compresed_image.fp.read())/1024,2), "KB") ... We can also download an image from the web and compresses it using the Python pillow library.
GeeksforGeeks
geeksforgeeks.org › python › how-to-compress-images-using-python-and-pil
How to compress images using Python and PIL? - GeeksforGeeks
July 15, 2025 - # run this in any directory # add -v for verbose # get Pillow (fork of PIL) from # pip before running --> # pip install Pillow # import required libraries import os import sys from PIL import Image # define a function for # compressing an image def compressMe(file, verbose = False): # Get the path of the file filepath = os.path.join(os.getcwd(), file) # open the image picture = Image.open(filepath) # Save the picture with desired quality # To change the quality of image, # set the quality variable at # your desired level, The more # the value of quality variable # and lesser the compression pi
Medium
yldrykuru.medium.com › optimize-jpegs-with-python-reduce-file-size-by-40-without-quality-loss-e27d6343e6ea
Optimize JPEGs with Python: Reduce File Size by 40% Without Quality Loss | by Yıldıray Kuru | Medium
June 12, 2025 - import os from PIL import Image import zstandard as zstd import piexif def optimize_jpeg(input_path: str, temp_path: str): image = Image.open(input_path) if "exif" in image.info: piexif.remove(input_path) image.save(temp_path, format="JPEG", quality=85, optimize=True) print(f"[1] Optimized JPEG: {temp_path}") def compress_zstd(input_path: str, output_path: str, level: int = 19): with open(input_path, "rb") as f: jpeg_data = f.read() cctx = zstd.ZstdCompressor(level=level) compressed = cctx.compress(jpeg_data) with open(output_path, "wb") as f: f.write(compressed) print(f"[2] Zstd Compressed: {
GitHub
github.com › evgenyneu › image_compressor_python
GitHub - evgenyneu/image_compressor_python: A Python program that compresses an image using singular value expansion · GitHub
A Python program that compresses an image using singular value expansion - evgenyneu/image_compressor_python
Author evgenyneu
Javatpoint
javatpoint.com › how-to-compress-images-in-python
How to Compress Images in Python - Javatpoint
How to Compress Images in Python with tutorial, tkinter, button, overview, canvas, frame, environment set-up, first python program, etc.
Understanding Data
understandingdata.com › posts › how-to-easily-resize-compress-your-images-in-python
How To Easily Resize & Compress Your Images In Python
As different social media platforms often require different image and width formats, resizing images automatically with python can definitely save you time. To learn how to resize a single image. To learn how to resize multiple images within the current working directory. from PIL import Image import PIL import os import glob · As well as compressing an image, we can also re-size the image to be either: A specific base width. A specific base height. base_width = 360 image = Image.open('example-image.jpg') width_percent = (base_width / float(image.size[0])) hsize = int((float(image.size[1]) * float(width_percent))) image = image.resize((base_width, hsize), PIL.Image.ANTIALIAS) image.save('resized_compressed_image.jpg')
TutorialsPoint
tutorialspoint.com › how-to-compress-images-using-python-and-pil
How to Compress Images Using Python and PIL?
July 20, 2023 - from PIL import Image import io ... Image Info:") print(f"Dimensions: {original_img.size}") # Method 1: Resize the image width, height = original_img.size new_size = (width//2, height//2) resized_img = original_img.resize(new_size) ...
Aspose
products.aspose.com › aspose.imaging › python via .net › compress › jpeg
JPEG Images Compression with Python | products.aspose.com
1 month ago - Achieving a balance between file size and image quality requires a careful selection of algorithms and compression levels. To compress images in JPEG format, we’ll employ Aspose.Imaging for Python via .NET API which is a feature-rich, powerful and easy to use image manipulation and conversion API for Python platform.
Aspose
blog.aspose.com › aspose.blogs › compress images in python
Compress Images in Python | Compress PNG, JPG and TIF
July 7, 2023 - The following code sample shows how to compress an image in Python. To compress images of other formats, we will use the respective ImageOption class. For example, to compress JPG images, we will use JpegOptions and for Tiff images, we will use TiffOptions class.