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

Python3.8使用Pillow调整图片大小时触发TypeError错误求助

错误原因

你遇到的报错是因为Pillow的resize()方法要求传入的尺寸元组里的宽、高参数都必须是整数类型。你的代码中通过比例计算得到的height是浮点数类型,不符合参数要求,因此触发类型错误。

修复方案

只需要将计算得到的高度转换为整数即可,你可以根据精度需求选择取整方式:

  • 直接截断取整:用int()包裹高度计算表达式
  • 四舍五入取整:用round()包裹高度计算表达式,图像比例还原效果更好

修正后的完整代码如下:

from PIL import Image
imgwidth = 800
img = Image.open('img/2.jpeg')
concat = (imgwidth/img.size[0])
# 这里将计算结果转换为整数
height = int(float(img.size[1])*float(concat))
# 若后续升级Pillow到9.1.0及以上版本,可将Image.ANTIALIAS替换为Image.Resampling.LANCZOS
img = img.resize((imgwidth,height), Image.ANTIALIAS)
img.save('output.jpg')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:45:04