简体   繁体   中英

Lower the resolution of an image to a specific number of pixels in Python

I'm trying to lower the resolution of images to 250.000 pixels using Python but I don't want them to have a specific height or width so that it depends on the image in question. I've been looking at options like resize_thumbnail or use Pillow but in both I have to set the maximum width or height.

You must know the resolution of the image you begin with, therefore scaling it to 250k pixels is just a matter of proportions.

# With Pillow you can read the size property of the image
width, height = image.size
res_0 = width * height
res_1 = 250000

# You need a scale factor to resize the image to res_1
scale_factor = (res_1/res_0)**0.5
resized = image.resize(width * scale_factor, height * scale_factor)

Out of curiosity I digged a little deeper to resize to the highest resolution that keeps the aspect ratio of the original image, if it exists.
An image with an aspect ratio of W:H can be divided in W×H squares whose side is the GCD of the width and height of the resolution.
After finding W and H, what's left to do is to calculate the highest multiples of W and H that fit the given resolution, in our case 250k pixels.

import math

# With Pillow you can read the size property of the image  
width, height = 2538, 1080
res_0 = width * height
res_1 = 1920*1080 # 518400

# You need a scale factor to resize the image to Res1
scale_factor = (res_1/res_0)**0.5
ratio = width/height

# The 
max_width = width * scale_factor
max_height = height * scale_factor

# Greates Common Divider and W:H
GCD = math.gcd(width, height)
W = width / GCD
H = height / GCD

ratio_width = math.floor(max_resized[0] / W) * W
ratio_height = math.floor(max_resized[1] / H) * H

scaled_size = (max_width, max_height)
# If GCD > 1 the image can be scaled keeping the original aspect ratio
# otherwise it'll approximated
if (GCD > 1):
    scaled_size = (ratio_width, ratio_height)
    
resized = image.resize(scaled_size)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM