PIL裁剪/缩略图的填充颜色

问题描述:

我正在拍摄图像文件,并使用以下PIL代码对其进行缩略图处理和剪切:

I am taking an image file and thumbnailing and cropping it with the following PIL code:

        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通道.

This works great, except when the image isn't the same aspect ratio, the difference is filled in with a black color (or maybe an alpha channel?). I'm ok with the filling, I'd just like to be able to select the fill color -- or better yet an alpha channel.

输出示例:

如何指定填充颜色?

我稍稍更改了代码,以允许您指定自己的背景颜色,包括透明度. 该代码将指定的图像加载到PIL.Image对象中,根据给定的大小生成缩略图,然后将图像粘贴到另一个完整尺寸的表面中. (请注意,用于颜色的元组也可以是任何RGBA值,我刚刚使用的alpha/透明度为0的白色.)

I altered the code just a bit to allow for you to specify your own background color, including transparency. The code loads the image specified into a PIL.Image object, generates the thumbnail from the given size, and then pastes the image into another, full sized surface. (Note that the tuple used for color can also be any RGBA value, I have just used white with an alpha/transparency of 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')