dav*_*ave 2 python resize image thumbnails aspect-ratio
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')
Run Code Online (Sandbox Code Playgroud)
这是我当前的缩略图生成脚本.它的工作方式是:
如果您的图像为400x300,并且您希望缩略图为100x100,则原始图像的左侧和右侧将需要50个像素.因此,将其调整为300x300.这使原始图像具有与新缩略图相同的纵横比.之后,它会将其缩小到所需的缩略图大小.
这样做的好处是:
如果你要将400x300图像缩小到100x100,它看起来会变暗.如果您从0x0坐标获取缩略图,您将获得图像的左上角.通常,图像的焦点是中心.
我希望能够为脚本提供任何宽高比的宽度/高度.例如,如果我想将400x300图像的大小调整为400x100,它应该从图像的左侧和右侧刮掉150px ...
我想不出办法做到这一点.有任何想法吗?
Mar*_*air 16
您只需要比较纵横比 - 取决于哪个更大,它将告诉您是否切掉侧面或顶部和底部.例如怎么样:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6285 次 |
| 最近记录: |