如何将图片调整到给定的边界区域,最简单的方法是什么?

3

I'd like to create a function, like:

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

可以指定文件并进行调整大小。

当前的函数运行良好,但在必要时未执行裁剪操作。

如果提供了一个矩形图像,并需要进行正方形调整大小(宽度=高度),则需要进行一些中心加权裁剪。

1个回答

6

在缩放图片之前,您需要正确地裁剪图片。基本思想是确定源图像的最大矩形区域,该区域与缩略图图像具有相同的宽高比,然后在将其调整为缩略图尺寸之前裁剪掉(裁剪)其周围的任何多余部分。这是一个可以计算出这种裁剪区域大小和位置的函数:

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(...)

你可以通过计算需要缩放的比例,使得结果能够适应缩略图的边界而不必完全填充,从而避免裁剪原始图像。 - martineau
对于任何感兴趣的人,我使用 Ruby 做了类似的事情: http://stackoverflow.com/a/14917213/407213 - Dorian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接