簡體   English   中英

Python / Pillow:如何縮放圖像

[英]Python / Pillow: How to scale an image

假設我的圖像是2322像素x 4128像素。 如何縮放它以使寬度和高度都小於1028px?

我將無法使用Image.resizehttps://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.resize ),因為這需要我同時給出新的寬度和高度。 我打算做的是(下面的偽代碼):

if (image.width or image.height) > 1028:
    if image.width > image.height:
        tn_image = image.scale(make width of image 1028)
        # since the height is less than the width and I am scaling the image
        # and making the width less than 1028px, the height will surely be
        # less than 1028px
    else: #image's height is greater than it's width
        tn_image = image.scale(make height of image 1028)

我猜我需要使用Image.thumbnail ,但根據這個例子( http://pillow.readthedocs.org/en/latest/reference/Image.html#create-thumbnails )和這個答案( 我如何調整大小使用PIL並保持其寬高比? )的圖像,提供寬度和高度以創建縮略圖。 是否有任何功能可以采用新的寬度或新的高度(不是兩者)並縮放整個圖像?

Noo需要重新發明輪子, Image.thumbnail方法可用於此:

maxsize = (1028, 1028)
image.thumbnail(maxsize, PIL.Image.ANTIALIAS)

確保最終尺寸不大於給定邊界,同時保持縱橫比。

指定PIL.Image.ANTIALIAS應用高質量的下采樣過濾器以獲得更好的調整大小結果,您可能也需要它。

使用Image.resize,但同時計算寬度和高度。

if image.width > 1028 or image.height > 1028:
    if image.height > image.width:
        factor = 1028 / image.height
    else:
        factor = 1028 / image.width
    tn_image = image.resize((int(image.width * factor), int(image.height * factor)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM