Models of image compress12/29/2023 First, we use the Image.open() method to load the image to the memory, we get the size of the image file using os.path.getsize() so we can later compare this size with the new generated file's size.New_filename = f"% of the original image size.")Ī giant function that does a lot of stuff, let's cover it in more detail: # make new filename appending _compressed to the original file name Img = img.resize((width, height), Image.ANTIALIAS)įilename, ext = os.path.splitext(image_name) # if width and height are set, resize with them instead Img = img.resize((int(img.size * new_size_ratio), int(img.size * new_size_ratio)), Image.ANTIALIAS) # if resizing ratio is below 1.0, then multiply width & height with this ratio to reduce image size Print(" Size before compression:", get_size_format(image_size)) # print the size before compression/resizing Next, let's make our core function for compressing images: def compress_img(image_name, new_size_ratio=0.9, quality=90, width=None, height=None, to_jpg=True): Open up a new Python file and import it: import osīefore we dive into compressing images, let's grab a function from this tutorial to print the file size in a friendly format: def get_size_format(b, factor=1024, suffix="B"):įor unit in : You can also specify the quality ratio.Īlright, to get started, let's install Pillow: $ pip install Pillow You can compress the image and resize it with a scaling factor or exact width and height. I made the code for this tutorial as flexible as possible. 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. You're free how to use the code of this tutorial. However, in this tutorial, you will learn to reduce image file size in Python using the Pillow library. There are a lot of tools online that offer this service most of them are a great option if you want to minimize your images quickly and reliably. Image compression is the process of minimizing the size of an image without degrading the image quality. Disclosure: This post may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |