简体   繁体   English

如何在 Python PIL 中将图像调整为特定大小而不失真?

[英]How to resize images to certain size in Python PIL without distortion?

I'm trying to crop images to 1000, 1000 using PIL in Python.我正在尝试使用 Python 中的 PIL 将图像裁剪为 1000、1000。

However, it always stretches the image to match the dimensions rather than cropping.但是,它总是拉伸图像以匹配尺寸而不是裁剪。 Current code below.当前代码如下。

Preferably, I would like to crop the original images evenly on the right and left while extending or reducing the height to 1000.最好,我想在将高度扩展或降低到 1000 的同时,在左右均匀裁剪原始图像。

from PIL import Image
img = Image.open('image.jpg')
new_img = img.resize((1000,1000))
new_img.save("image.jpg", "JPEG", optimize=True)
new_img.show()

You can use the image.crop method to crop the sides, followed by a image.resize to extend or reduce the height to 1000:您可以使用image.crop方法裁剪边,然后使用image.resize将高度扩展或减小到 1000:

(width, height) = img.size
left = int((width - 1000)/2)
right = left + 1000
new_img = img.crop((left, 0, right, height))
new_img = new_img.resize((1000,1000))

In the python you can use the resize image with PILL library in this you want to import the PILL module在 python 中,您可以在要导入 PILL 模块的情况下使用带有 PILL 库的调整大小图像

from PIL import Image
im = Image.open("images/cat.jpg")
im.show()
resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))
resized_im.show()
resized_im.save('resizedBeach1.jpg')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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