2010-10-06 36 views
2

我想創建一個功能,如:Python中將圖像大小調整爲給定有界區域的最簡單方法是什麼?

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

當一個文件可以給出調整。

目前的功能很好,除非它在必要時不裁剪。

在給出矩形圖像並且需要方形調整大小(寬度=高度)的情況下,必須進行一些居中加權的裁剪。

我該怎麼做?

謝謝!

回答

4

你需要在調整大小之前正確地裁剪圖像。基本思路是確定具有與縮略圖圖像相同縱橫比(寬高比)的源圖像的最大矩形區域,然後在調整縮略圖的尺寸之前裁剪(剪裁)任何多餘的周圍區域。這裏是將計算這樣的剪切區域的大小和位置的功能:

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's dimensions 
      thumbwidth, thumbheight are thumbnail image's 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 compute half the size difference of the image & crop area 
    dx = (imagewidth-cropwidth)/2 
    dy = (imageheight-cropheight)/2 

    # return bounding box of crop area 
    return dx, dy, dx+cropwidth, dy+cropheight 

if __name__=='__main__': 

    print "===" 
    bbox = cropbbox(1024, 768, 128, 128) 
    print "cropbbox(1024, 768, 128, 128):", bbox 

    print "===" 
    bbox = cropbbox(768, 1024, 128, 128) 
    print "cropbbox(768, 1024, 128, 128):", bbox 

    print "===" 
    bbox = cropbbox(1024, 1024, 96, 128) 
    print "cropbbox(1024, 1024, 96, 128):", bbox 

    print "===" 
    bbox = cropbbox(1024, 1024, 128, 96) 
    print "cropbbox(1024, 1024, 128, 96):", bbox 

確定裁剪區域後,調用im.crop(bbox)然後調用圖像im.thumbnail(...)返回。

+0

嘿,這真的很有幫助。非常感謝。 – ensnare 2010-10-11 14:49:24

+0

您可以避免必須裁剪原始圖像,以確定縮放圖像的大小,以便將結果放在縮略圖的邊界內,但不一定完全填滿。 – martineau 2010-10-11 20:06:58

+0

對於任何感興趣的人,我使用Ruby做了類似的事情:http://stackoverflow.com/a/14917213/407213 – Dorian 2013-02-17 18:44:52

0

您有Image#crop。這是你的問題嗎?或如何計算作物座標? (這取決於你想如何製作它)

相關問題