python中_47

python中_47在 Python 中 可以使用 Pillow 库来缩小图片并保持其原比例 以下是使用 Pillow 库缩小图片的步骤和代码示例 1 安装 Pillow 库 pip install Pillow 2 导入 Pillow 库和相关模块 pythonfrom PIL import Image 3 打开图片文件 pythonimage Image open input

在Python中,可以使用Pillow库来缩小图片并保持其原比例。以下是使用Pillow库缩小图片的步骤和代码示例:

1. 安装Pillow库:

pip install Pillow

2. 导入Pillow库和相关模块:

python

from PIL import Image

3. 打开图片文件:

python

image = Image.open("input.jpg")

4. 获取原始图片的宽度和高度:

python

width, height = image.size

5. 设置缩小后的目标宽度和高度。例如,将图片缩小为原来的一半大小:

python

target_width = width // 2

target_height = height // 2

6. 使用`resize()`函数来缩小图片并保持原比例:

python

image.thumbnail((target_width, target_height), Image.ANTIALIAS)

7. 保存缩小后的图片:

python

image.save("output.jpg")

完整的代码示例:

python

from PIL import Image

打开图片文件

image = Image.open("input.jpg")

获取原始图片的宽度和高度

width, height = image.size

设置缩小后的目标宽度和高度

target_width = width // 2

target_height = height // 2

缩小图片并保持原比例

image.thumbnail((target_width, target_height), Image.ANTIALIAS)

保存缩小后的图片

image.save("output.jpg")

以上步骤和代码可以帮助你使用Python和Pillow库来缩小图片。

编程小号
上一篇 2026-03-26 08:08
下一篇 2026-03-26 08:04

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/67822.html