You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Pillow库thumbnail方法返回None的问题求助

Fixing Pillow's thumbnail() Returning None Issue

Hey there! I totally get where you're coming from—switching from resize() to thumbnail() to preserve aspect ratio makes perfect sense, but that None return value can throw you for a loop. Let's break down what's happening and fix this quickly.

The Core Problem

Unlike resize() (which creates and returns a new Image object with your adjusted dimensions), thumbnail() works in-place: it modifies the original Image object directly and doesn't return anything (hence the None you're seeing). That's the key difference that's tripping you up!

Correct Usage of thumbnail()

Here's how to use it properly with your Python 3.5 + Pillow 5.0 setup:

  1. Open your image as usual
  2. Call thumbnail() directly on the image object (don't assign the result to a new variable)
  3. Save the modified original object

Example Code

First, let's look at the mistake that causes None:

from PIL import Image

# ❌ Wrong: thumbnail() doesn't return a new image, so resized_img is None
img = Image.open("input.jpg")
resized_img = img.thumbnail((800, 600))
resized_img.save("output.jpg")  # This will throw an AttributeError!

Now the correct approach:

from PIL import Image

# ✅ Correct: thumbnail() modifies the img object in-place
img = Image.open("input.jpg")

# Set your max width/height (thumbnail will maintain aspect ratio automatically)
# Use Image.LANCZOS (or Image.ANTIALIAS, its alias in Pillow 5.0) for high-quality resizing
img.thumbnail((800, 600), resample=Image.LANCZOS)

# Save the now-resized image
img.save("output.jpg")

Bonus: Preserving the Original Image

If you don't want to modify the original image object (maybe you need to use it later), make a copy first:

from PIL import Image

img = Image.open("input.jpg")
# Create a duplicate to resize, leaving the original intact
img_copy = img.copy()
img_copy.thumbnail((800, 600), resample=Image.LANCZOS)
img_copy.save("output.jpg")

# Original image is still unmodified
img.save("original.jpg")

Why This Works

Pillow's thumbnail() is designed to be memory-efficient by modifying the existing image instead of creating a new one. The tradeoff is that it doesn't return a value—something easy to miss if you're used to resize()'s behavior.

内容的提问来源于stack exchange,提问作者Braden Holt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:13:43