Python PIL: cannot write mode RGBA as BMP

Python PIL: cannot write mode RGBA as BMP

作为一个python新手,一开始遇到了不少问题,这个问题是我在使用PIL库时出现的,但是在网上没有找到比较好的解决办法,所以在这里mark一下。

问题重现

在使用PIL中一些常见的“open”,”show”,”save”函数时,代码如下:

>>> from PIL import Image
>>> im=Image.open("test.png")
>>> im.show()
>>> im
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=521x391 at 0x37D75F8>
>>> im.save("test.bmp")

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    im.save("test.bmp")
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "C:\Python27\lib\site-packages\PIL\BmpImagePlugin.py", line 203, in _save
    raise IOError("cannot write mode %s as BMP" % im.mode)
IOError: cannot write mode RGBA as BMP
>>> 

出现了这个错误。

stackflow

cannot write mode RGBA as BMP pytesser

  1. i say that , must resize the image you can use plugins for edit image size before use it and read it , plugin like pil hope to work for you
    表示没看懂什么意思,只知道和size有关,我以为是图片的size要是4的倍数,试了试,不行。
  2. I had the same problem – issue was the transparency. (converting rbgy to rbg) Adding white background fixed it.
im = Image.open(C:\image.png)
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
print image_to_string(bg)

其实这个方案是可行的,但是它没有说清楚,没说为什么可以,所以当时就被我忽略掉了。其实是因为,png图像有RGBA四个通道,而BMP图像只有RGB三个通道,所以PNG转BMP时候程序不知道A通道怎么办,就会产生错误。

启示

我在另外一篇文章中得到了启示。
python Image库的使用

里面有一段转换图像格式的代码:

from PIL import Image
file_in = "test.png"
img = Image.open(file_in)
file_out = "test2.bmp"
print len(img.split())  # test
if len(img.split()) == 4:
    #prevent IOError: cannot write mode RGBA as BMP
    r, g, b, a = img.split()
    img = Image.merge("RGB", (r, g, b))
    img.save(file_out)
else:
    img.save(file_out)

程序检查通道数,来决定是直接转换成bmp还是丢弃A通道后转换成BMP,说明在含有A通道时,转换会失败。

结论

转换过程如下:

>>> from PIL import Image
>>> im=Image.open("test.png")
>>> r,g,b,a=im.split()
>>> im=Image.merge((r,g,b))

Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    im=Image.merge((r,g,b))
TypeError: merge() takes exactly 2 arguments (1 given)
>>> im=Image.merge("RGB",(r,g,b))
>>> im.save("test.bmp")
>>> 

参考

  1. cannot write mode RGBA as BMP pytesser
  2. Image 库的使用
  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值