【问题标题】:Reducing the width/height of an image to fit a given aspect ratio. How? - Python image thumbnails减小图像的宽度/高度以适应给定的纵横比。如何? - Python图像缩略图
【发布时间】:2011-06-12 06:38:25
【问题描述】:
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...

我想不出办法来做到这一点。有什么想法吗?

【问题讨论】:

  • 你(和@Mark Longair 在他的回答中)所说的调整图像大小通常被称为裁剪它。调整大小通常意味着缩放一个或两个维度。
  • @martineau:嗯,他正在裁剪然后调整它的大小 - 我只是在调用 crop 时将变量名称保留为 resize 以与问题保持一致......
  • 您可能只想考虑缩放原始图像,使其适合缩略图的边界,而不是剪掉其中的一部分。这可以在缩略图的矩形中留下一些未使用的空间,但避免删除原始的任何部分。这可以通过比较纵横比来确定适当的比例因子(将缩放最长尺寸以适应缩略图的相应尺寸(宽度或高度)的比例因子)来完成。

标签: python image resize thumbnails aspect-ratio


【解决方案1】:

您只需要比较纵横比 - 取决于哪个更大,这将告诉您是切掉侧面还是顶部和底部。例如怎么样:

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')

【讨论】:

  • @greg:没问题 - 如果你也能接受答案就好了,在这种情况下:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 2016-05-18
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2013-07-07
  • 2017-02-13
相关资源
最近更新 更多