2012-07-26 56 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')