如何使用Python PIL在不扭曲图像的情况下生成1000x1000缩略图



我试图在Python PIL中导出1000x1000个图像缩略图,而不会扭曲原始图像。

如果原始图像的尺寸超过1000x1000,则此代码有效。

(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))

然而,如果图像的尺寸低于此值,例如800 x 400,则它们会被拉伸和扭曲。

根据我从你的问题中了解到的,无论图像的大小如何,都需要裁剪成1000x1000的图像。

一种方法是先将图像裁剪成正方形,然后将其调整为1000x1000。

(width, height) = img.size
if width < height: # if width is smaller than height, crop height
h = int((height - width)/2)
new_img = img.crop((0, h, width, width+h))
else: # if height is smaller than width, crop width
w = int((width - height)/2)
new_img = img.crop((w, 0, height+w, height))
# resize to required size
new_img = new_img.resize((1000,1000))

先收割后扩大比先扩大后收割更有效率。这是因为在第二种情况下,您在较大的图像上进行图像操作(即裁剪(,这比裁剪较小的图像占用更多的资源(CPU、RAM等(。如果你正在处理大量的图像,这可能会导致处理时间的显著差异。

相关内容

最新更新