Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails(减小图像的宽度/高度以适应给定的纵横比。如何?-巨蟒图像缩略图)
本文介绍了减小图像的宽度/高度以适应给定的纵横比。如何?-巨蟒图像缩略图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import Image
image = Image.open('images/original.jpg')
width = image.size[0]
height = image.size[1]
if width > height:
difference = width - height
offset = difference / 2
resize = (offset, 0, width - offset, height)
else:
difference = height - width
offset = difference / 2
resize = (0, offset, width, height - offset)
thumb = image.crop(resize).resize((200, 200), Image.ANTIALIAS)
thumb.save('thumb.jpg')
这是我当前的缩略图生成脚本。它的工作方式是:
如果您有一个400x300的图像,并且您想要一个100x100的缩略图,它将从原始图像的左侧和右侧移去50个像素。因此,将其大小调整为300x300。这为原始图像提供了与新缩略图相同的纵横比。之后,它会将其缩小到所需的缩略图大小。
这样做的好处是:
- 缩略图取自图像中心
- 长宽比不会搞砸
如果将400x300的图像缩小到100x100,它看起来会被挤压。如果从0x0坐标获取缩略图,则会得到图像的左上角。通常,图像的焦点在中心。
我想要做的是为脚本提供任意长宽比的宽/高。例如,如果我想要将400x300图像的大小调整为400x100,它应该将图像的左侧和右侧刮掉150px...
我想不出一个办法来做这件事。有什么想法吗?
推荐答案
您只需比较纵横比--根据哪个更大,这将告诉您是剪掉侧面还是顶部和底部。例如:
import Image
image = Image.open('images/original.jpg')
width = image.size[0]
height = image.size[1]
aspect = width / float(height)
ideal_width = 200
ideal_height = 200
ideal_aspect = ideal_width / float(ideal_height)
if aspect > ideal_aspect:
# Then crop the left and right edges:
new_width = int(ideal_aspect * height)
offset = (width - new_width) / 2
resize = (offset, 0, width - offset, height)
else:
# ... crop the top and bottom:
new_height = int(width / ideal_aspect)
offset = (height - new_height) / 2
resize = (0, offset, width, height - offset)
thumb = image.crop(resize).resize((ideal_width, ideal_height), Image.ANTIALIAS)
thumb.save('thumb.jpg')
这篇关于减小图像的宽度/高度以适应给定的纵横比。如何?-巨蟒图像缩略图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:减小图像的宽度/高度以适应给定的纵横比。如何?-巨蟒图像缩略图
基础教程推荐
猜你喜欢
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
