これは2段階で行うのが最も簡単です。まずクロップしてからサムネイルを生成します。指定されたアスペクト比に切り取るのは一般的には十分ですが、実際にはピローにはその機能があるはずですが、私が知っている限り、そこにはありません。ここでは、単純な実装は、Imageクラス上に猿パッチを当てています:あなたはImage.Image.crop_to_aspect = _Image.crop_to_aspect`、なぜ `使用しないのはなぜ
from PIL import Image
class _Image(Image.Image):
def crop_to_aspect(self, aspect, divisor=1, alignx=0.5, aligny=0.5):
"""Crops an image to a given aspect ratio.
Args:
aspect (float): The desired aspect ratio.
divisor (float): Optional divisor. Allows passing in (w, h) pair as the first two arguments.
alignx (float): Horizontal crop alignment from 0 (left) to 1 (right)
aligny (float): Vertical crop alignment from 0 (left) to 1 (right)
Returns:
Image: The cropped Image object.
"""
if self.width/self.height > aspect/divisor:
newwidth = int(self.height * (aspect/divisor))
newheight = self.height
else:
newwidth = self.width
newheight = int(self.width/(aspect/divisor))
img = self.crop((alignx * (self.width - newwidth),
aligny * (self.height - newheight),
alignx * (self.width - newwidth) + newwidth,
aligny * (self.height - newheight) + newheight))
return img
Image.Image.crop_to_aspect = _Image.crop_to_aspect
これを考えると、あなただけの
cropped = img.crop_to_aspect(200,200)
cropped.thumbnail((200, 200), Image.ANTIALIAS)
を書くことができます'Image.Image'を継承せず、その新しいクラスを使用しますか? – dtgq
Pillowでイメージを作成する標準的な方法は、イメージモジュール(open()、new()など)のファクトリ関数を使用しているため、常に 'Image'オブジェクトが作成されます。しかし、それを得るためのより良い方法があるかもしれません。 –