2010-11-18 98 views
4

想象一下在完全透明的背景上消失的黑色阴影的红色圆圈。当我用PIL打开并重新保存图像时,背景保持完全透明,但阴影变为全黑。看来,甚至没有改变图像Python PIL - 具有不透明度> 0的所有PNG区域都将其不透明度设置为1

问题:

image = Image.open('input.png') 
image = image.convert('RGBA') 
image.save('output.png') 

我想保留的图像准确地看着原来如此,我可以裁剪或调整其大小。

编辑:这是一个演示效果的PNG。它通过使用PNGNQ转换为8位。

alt text

当使用上述Python代码它出来,如下所示:

alt text

+0

@Kyle:你会后'input.png'和'output.png'?我似乎无法重现这个问题。 – unutbu 2010-11-18 18:34:10

+0

我编辑文件以“编辑”敏感的东西和重新生成的图像工作正常。所以我意识到input.png是一个8位的PNG,我认为考虑到它们在网络图形之外是非常罕见的,所以将它们考虑在内是非常费力的。 – 2010-11-18 19:07:22

+0

'.png'格式的什么味道是'input.png' - 它以什么格式开头? – martineau 2010-11-18 19:10:50

回答

6

它看起来像PIL目前不支持PNG8的完整alpha。

有一个补丁这里只读支持:http://mail.python.org/pipermail/image-sig/2010-October/006533.html

如果你感觉闹腾,你可以猴补丁PIL:

from PIL import Image, ImageFile, PngImagePlugin 

def patched_chunk_tRNS(self, pos, len): 
    i16 = PngImagePlugin.i16 
    s = ImageFile._safe_read(self.fp, len) 
    if self.im_mode == "P": 
     self.im_info["transparency"] = map(ord, s) 
    elif self.im_mode == "L": 
     self.im_info["transparency"] = i16(s) 
    elif self.im_mode == "RGB": 
     self.im_info["transparency"] = i16(s), i16(s[2:]), i16(s[4:]) 
    return s 
PngImagePlugin.PngStream.chunk_tRNS = patched_chunk_tRNS 

def patched_load(self): 
    if self.im and self.palette and self.palette.dirty: 
     apply(self.im.putpalette, self.palette.getdata()) 
     self.palette.dirty = 0 
     self.palette.rawmode = None 
     try: 
      trans = self.info["transparency"] 
     except KeyError: 
      self.palette.mode = "RGB" 
     else: 
      try: 
       for i, a in enumerate(trans): 
        self.im.putpalettealpha(i, a) 
      except TypeError: 
       self.im.putpalettealpha(trans, 0) 
      self.palette.mode = "RGBA" 
    if self.im: 
     return self.im.pixel_access(self.readonly) 
Image.Image.load = patched_load 

Image.open('kHrY6.png').convert('RGBA').save('kHrY6-out.png') 
+0

它就像一个魅力!谢谢! – 2012-01-04 00:28:34

0

我认为这个问题已经有所解决,但它可能是你需要设置alpha通道的深度?