PIL会将图像缩放为我给定的确切尺寸吗?还是说如果我使用Image.ANTIALIAS
参数,它会尝试保持长宽比?
Image.ANTIALIAS
参数来保持长宽比例。PIL会将图像缩放为我给定的确切尺寸吗?还是说如果我使用Image.ANTIALIAS
参数,它会尝试保持长宽比?
Image.ANTIALIAS
参数来保持长宽比例。使用缩略图方法,它将保持纵横比:
image = Image.open(source_path)
image.thumbnail((500,500), Image.ANTIALIAS)
image.save(dest_path, "JPEG")
使用PIL中的Image.resize可以按照指定的大小调整图像,而不会自行处理纵横比。
自Pillow 8.3以来,有以下方法可将图像按比例缩放以适合给定的框。
image = ImageOps.contain(image, (2048,2048))
ImageOps.fit(image, size)
也可能会有帮助。 - talljoshim = PIL.Image.open("email.jpg"))
width, height = im.size
im = im.resize((width//2, height//2))
这里高度和宽度被相同的数值除开,保持了相同的比例。
im = im.resize((width//2, height//2))
- York Yang好的,这需要几行代码才能得到你想要的结果。
首先找到比例,然后确定你想要的图像的一个维度(高度或宽度)。在我的情况下,我想要高度为100像素,让宽度相应调整,并最终使用该比例来找到新的高度或新的宽度。
所以首先找到图像的尺寸:
width, height = logo_img.size
ratio = width / height
然后,固定其中一个维度:
new_height = 100
接着计算该高度下的新宽度:
new_width = int(ratio * new_height)
logo_img = logo_img.resize((new_width, new_height))
这取决于您的需求,如果您希望可以设置固定的高度和宽度,或者如果您希望使用 aspect-ratio 进行调整大小。
对于按照纵横比调整大小,您可以尝试以下代码:
将新图像的宽度和高度均减半:
from PIL import Image
im = Image.open("image.jpg")
resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))
#Save the cropped image
resized_im.save('resizedimage.jpg')
使用固定宽度和比例动态高度进行调整:
from PIL import Image
new_width = 300
im = Image.open("img/7.jpeg")
concat = int(new_width/float(im.size[0]))
size = int((float(im.size[1])*float(concat)))
resized_im = im.resize((new_width,size), Image.ANTIALIAS)
#Save the cropped image
resized_im.save('resizedimage.jpg')
ImageOps.fit
不就是Image.thumbnail
吗? - CrashalotImage.thumbnail
与ImageOps.contain
类似。一个主要的区别是Image.thumbnail
会直接在原图上进行编辑,而ImageOps.contain
则会创建一个新的图像。此外,Image.thumbnail
的文档中指出生成的缩略图大小不会超过给定的尺寸。但实际上我不知道它是否会比指定的尺寸更小。 - talljosh一个完整的示例:
import PIL.Image
class ImageUtils(object):
@classmethod
def resize_image(cls, image: PIL.Image.Image, width=None, height=None) -> PIL.Image.Image:
if height is None and width is not None:
height = image.height * width // image.width
elif width is None and height is not None:
width = image.width * height // image.height
elif height is None and width is None:
raise RuntimeError("At lease one of width and height must be present")
return image.resize((width, height))
def main():
ImageUtils.resize_image(PIL.Image.open("old.png"), width=100).save("new.png")
if __name__ == '__main__':
main()
Img1 = img.resize((img.size),PIL.Image.ANTIALIAS)