Eri*_*rik 8 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')
Run Code Online (Sandbox Code Playgroud)
这种方法效果很好,除非图像长宽比不同时,差异用黑色填充(或者可能是alpha通道?).我很满意填充,我只想选择填充颜色 - 或者更好的是填充alpha通道.
输出示例:

如何指定填充颜色?
Eli*_*Eli 15
我稍微更改了代码,以便您指定自己的背景颜色,包括透明度.代码将指定的图像加载到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')
Run Code Online (Sandbox Code Playgroud)
fra*_*xel 14
将paste您的缩放缩放图像重新设置到新图像上会更容易,即您想要的颜色(和Alpha值).
你可以创建一个图像,并在RGBA像这样的元组中拼出它的颜色:
Image.new('RGBA', size, (255,0,0,255))
Run Code Online (Sandbox Code Playgroud)
这里没有透明度,因为alpha波段设置为255.但背景将为红色.使用此图像粘贴到我们可以创建任何颜色的缩略图,如下所示:

如果我们将alpha波段设置为0,我们可以paste在透明图像上,并获得:

示例代码:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16016 次 |
| 最近记录: |