深度阅读

how to resize an image using python

作者
作者
2023年08月22日
更新时间
11.07 分钟
阅读时间
0
阅读量

To resize an image using Python, you can use the Pillow library. Here’s an example code snippet that resizes an image to a new width of 500 pixels while keeping the aspect ratio:

from PIL import Image

# Open the image file
image = Image.open('my_image.jpg')

# Get the aspect ratio of the original image
aspect_ratio = image.width / image.height

# Calculate the new height based on the new width and aspect ratio
new_width = 500
new_height = int(new_width / aspect_ratio)

# Resize the image
new_image = image.resize((new_width, new_height))

# Save the resized image
new_image.save('my_resized_image.jpg')

In this code, PIL.Image.open() is used to open the input image, image.width and image.height are used to get the original image’s dimensions, and image.resize() is used to resize the image to the desired size. Finally, new_image.save() is used to save the resized image to a new file.

Note that Pillow provides several different resizing methods, which you can specify by passing an optional resample parameter to image.resize(). The default method is Image.BICUBIC.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。