【问题标题】:What's the simplest way to resize an image to a given bounded area?将图像大小调整为给定有界区域的最简单方法是什么?
【发布时间】:2025-12-02 04:55:01
【问题描述】:

我想创建一个函数,比如:

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

在哪里可以给定文件并调整其大小。

当前功能很好用,只是在必要时不裁剪。

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

【问题讨论】:

    标签: python imaging image-resizing python-imaging-library


    【解决方案1】:

    在调整图像大小之前,您需要正确裁剪图像。基本思想是确定与缩略图图像具有相同纵横比(宽度与高度)比率的源图像的最大矩形区域,然后在调整到缩略图尺寸之前修剪(裁剪)其周围的任何多余部分)。下面是一个函数,它将计算这样一个裁剪区域的大小和位置:

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

    【讨论】:

    • 您可以避免裁剪原始图像,方法是确定缩放多少以使结果适合缩略图的边界,但不一定要完全填充。
    • 对于任何感兴趣的人,我使用 Ruby 做了类似的事情:*.com/a/14917213/407213
    最近更新 更多