write a python script that takes an image and reduces its detentions until it is lower…
- User
write a python script that takes an image and reduces its detentions until it is lower than 100kb
- Assistant
To reduce the dimensions of an image until the file size is lower than 100 KB, you can utilize the
PIL(Python Imaging Library) library, which is now known asPillow. First, you need to install the library by running:pip install PillowHere's a Python script that takes an image file as input, resizes it, and saves the result as a new image file:
from PIL import Image import os def resize_image(input_image_path, output_image_path): image = Image.open(input_image_path) image_width, image_height = image.size factor = 1 while True: factor = factor - 0.05 new_image = image.resize((int(image_width * factor), int(image_height * factor)), Image.ANTIALIAS) new_image.save(output_image_path, quality=85, optimize=True) if os.stat(output_image_path).st_size < 100*1024: break print(f"Resized image saved to {output_image_path}") if __name__ == '__main__': resize_image("input_image.jpg", "output_image.jpg")Replace "input_image.jpg" with the path of your input image and "output_image.jpg" with the path where you want to save the resized image. The script will load the image, reduce its dimensions by a factor (5% at a time in this case), and save the new image with specified quality (85 in this case) and optimization. If the file size is still larger than 100 KB after resizing, the resizing process repeats until the file size is under the desired threshold.
You may need to change the quality, optimization, and resizing factor in the script based on your specific use case and the sizes of your input images.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.