質問

次のような関数を作成したいと思います。

def generateThumbnail(self, width, height):
     """
     Generates thumbnails for an image
     """
     im = Image.open(self._file)
     im.thumbnail((width, height), Image.ANTIALIAS)
     im.save(self._path + str(width) + 'x' + 
             str(height) + '-' + self._filename, "JPEG")

ファイルを指定してサイズ変更できる場合。

現在の機能は、必要に応じて収穫しないことを除いて、うまく機能します。

長方形の画像が与えられ、正方形のサイズ変更が必要である場合(幅=高さ)、中心にある加重作物を行う必要があります。

役に立ちましたか?

解決

サイズを変更する前に、画像を適切にトリミングする必要があります。基本的なアイデアは、ソース画像の最大の長方形の領域を、サムネイル画像と同じアスペクト(幅と高さ)比を持つ最大の長方形の領域を決定し、サムネイルの寸法にサイズを変更する前に、その周りの過剰をトリミング(収穫)することです。このような作物エリアのサイズと場所を計算する関数は次のとおりです。

def cropbbox(imagewidth,imageheight, thumbwidth,thumbheight):
    """ cropbbox(imagewidth,imageheight, thumbwidth,thumbheight)

        Compute a centered image crop area for making thumbnail images.
          imagewidth,imageheight are source image dimensions
          thumbwidth,thumbheight are thumbnail image dimensions

        Returns bounding box pixel coordinates of the cropping area
        in this order (left,upper, right,lower).
    """
    # determine scale factor
    fx = float(imagewidth)/thumbwidth
    fy = float(imageheight)/thumbheight
    f = fx if fx < fy else fy

    # calculate size of crop area
    cropheight,cropwidth = int(thumbheight*f),int(thumbwidth*f)

    # for centering use half the size difference of the image and the crop area
    dx = (imagewidth-cropwidth)/2
    dy = (imageheight-cropheight)/2

    # return bounding box of centered crop area on source image
    return dx,dy, cropwidth+dx,cropheight+dy


if __name__=='__main__':

    print("===")
    bbox = cropbbox(1024,768, 128,128)
    print("cropbbox(1024,768, 128,128): {}".format(bbox))

    print("===")
    bbox = cropbbox(768,1024, 128,128)
    print("cropbbox(768,1024, 128,128): {}".format(bbox))

    print("===")
    bbox = cropbbox(1024,1024, 96,128)
    print("cropbbox(1024,1024, 96,128): {}".format(bbox))

    print("===")
    bbox = cropbbox(1024,1024, 128,96)
    print("cropbbox(1024,1024, 128,96): {}".format(bbox))

作物領域を決定した後、電話してください im.crop(bbox) そして、電話してください im.thumbnail(...) 画像が返されました。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top