填充PIL颜色/缩略图

时间:2012-07-26 06:59:17

标签: python-imaging-library

我正在拍摄图像文件并使用以下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

如何指定填充颜色?

2 个答案:

答案 0 :(得分:14)

我稍微更改了代码,以便您指定自己的背景颜色,包括透明度。 代码将指定的图像加载到PIL.Image对象中,从给定大小生成缩略图,然后将图像粘贴到另一个全尺寸表面。 (请注意,用于颜色的元组也可以是任何RGBA值,我刚使用白色,alpha /透明度为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')

答案 1 :(得分:13)

将您重新调整大小的缩略图图像paste放到新图像上会更容易一些,即您想要的颜色(和Alpha值)。

您可以创建一个图像,并在RGBA这样的元组中显示它的颜色:

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

这里没有透明度,因为alpha波段设置为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')