3
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 削る必要があります...

これを行う方法が思いつきません。何か案は?

4

1 に答える 1

26

縦横比を比較するだけで、どちらが大きいかに応じて、側面または上下のどちらを切り落とすかがわかります。例えばどうですか:

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')
于 2011-01-20T07:50:12.423 に答える