【问题标题】:Fill Color of PIL Cropping/ThumbnailingPIL 裁剪/缩略图的填充颜色
【发布时间】:2012-07-24 17:30:02
【问题描述】:

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

输出示例:

如何指定填充颜色?

【问题讨论】:

    标签: python-imaging-library


    【解决方案1】:

    我稍微修改了代码以允许您指定自己的背景颜色,包括透明度。 代码将指定的图像加载到 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')
    

    【讨论】:

      【解决方案2】:

      将调整大小的缩略图paste 转换为新图像会更容易一些,这就是您想要的颜色(和 alpha 值)。

      您可以创建一个图像,并在 RGBA 元组中指定其颜色,如下所示:

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

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

      【讨论】:

        猜你喜欢
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 1970-01-01
        • 2021-04-11
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多