2012-07-26 58 views
7

我以一個圖像文件和縮圖,並與下面的代碼PIL裁剪它:填寫PIL裁剪/彩色縮略

 image = Image.open(filename) 
     image.thumbnail(size, Image.ANTIALIAS) 
     image_size = image.size 
     thumb = image.crop((0, 0, size[0], size[1])) 
     offset_x = max((size[0] - image_size[0])/2, 0) 
     offset_y = max((size[1] - image_size[1])/2, 0) 
     thumb = ImageChops.offset(thumb, offset_x, offset_y)     
     thumb.convert('RGBA').save(filename, 'JPEG') 

這個偉大的工程,除了當圖像是不一樣的高寬比,這個區別是用黑色填充的(或者是一個alpha通道?)。我對填充很滿意,我只想選擇填充顏色 - 或者更好的是alpha通道。

輸出例如:

output

如何指定填充顏色?

回答

13

我改變了代碼只是爲了讓你指定你自己的背景顏色,包括透明度。 代碼將指定的圖像加載到PIL.Image對象中,根據給定尺寸生成縮略圖,然後將圖像粘貼到另一個完整大小的表面。 (請注意,用於色彩元組也可以是任何RGBA值,我剛纔用白色的0的α/透明度)


# assuming 'import from PIL *' is preceding 
thumbnail = Image.open(filename) 
# generating the thumbnail from given size 
thumbnail.thumbnail(size, Image.ANTIALIAS) 

offset_x = max((size[0] - thumbnail.size[0])/2, 0) 
offset_y = max((size[1] - thumbnail.size[1])/2, 0) 
offset_tuple = (offset_x, offset_y) #pack x and y into a tuple 

# create the image object to be the final product 
final_thumb = Image.new(mode='RGBA',size=size,color=(255,255,255,0)) 
# paste the thumbnail into the full sized image 
final_thumb.paste(thumbnail, offset_tuple) 
# save (the PNG format will retain the alpha band unlike JPEG) 
final_thumb.save(filename,'PNG') 
+0

巨大的。回想起來似乎很簡單 - 謝謝! – Erik 2012-07-29 16:59:06

11

它更容易一點paste你再將縮略圖圖像放到新圖像上,即您想要的顏色(和Alpha值)。

您可以創建一個圖像,並需要指明其顏色在RGBA元組是這樣的:

Image.new('RGBA', size, (255,0,0,255)) 

在這裏有沒有爲α帶被設置爲255沒有透明度,而且背景會是紅色的。使用此圖片粘貼到我們可以與任何像這樣的顏色創建縮略圖:

enter image description here

如果我們的alpha波段設置爲0,我們可以paste到透明的形象,並得到這樣的:

enter image description here

示例代碼:

import Image 

image = Image.open('1_tree_small.jpg') 
size=(50,50) 
image.thumbnail(size, Image.ANTIALIAS) 
# new = Image.new('RGBA', size, (255, 0, 0, 255)) #without alpha, red 
new = Image.new('RGBA', size, (255, 255, 255, 0)) #with alpha 
new.paste(image,((size[0] - image.size[0])/2, (size[1] - image.size[1])/2)) 
new.save('saved4.png')