PIL PNG格式通道问题的解决方法

近来研究图片的剪切拼接,用到PIL,在打开PNG格式保存为JPEG格式的图片发现报错:

 1 import os
 2 from PIL import Image
 3 
 4 
 5 im = Image.open(rE:\work\testcrop\test\hn1.png)
 6 img_size = im.size
 7 w = img_size[0] / 2.0
 8 h = img_size[1]
 9 x = 0
10 y = 0
11 print("图片宽度和高度分别是{}".format(img_size))
12 region = im.crop((x, y, x + w, y + h))
13 a = "1.jpeg"
14 region.save(a)

报错:

raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG

查资料发现是PNG有RGBA四个通道,而JPEG是RGB三个通道,所以PNG转BMP时候程序不知道A通道怎么办,就会产生错误。

解决方法就是检查通道数,舍弃A通道。

 1 import os
 2 from PIL import Image
 3 path = rE:\work\testcrop\test\hn2.png
 4 if png in path[-4:]:
 5     im = Image.open(path)
 6     r, g, b, a = im.split()
 7     im = Image.merge("RGB", (r, g, b))
 8     os.remove(path)
 9     im.save(path[:-4] + ".jpeg")
10 path = path[:-4] + ".jpeg"
11 im = Image.open(path)
12 img_size = im.size
13 w = img_size[0] / 2.0
14 h = img_size[1]
15 x = 0
16 y = 0
17 print("图片宽度和高度分别是{}".format(img_size))
18 region = im.crop((x, y, x + w, y + h))
19 a = "2.jpeg"
20 region.save(a)

至此解决。

参考:http://blog.csdn.net/smallflyingpig/article/details/56036771

文章来自:https://www.cnblogs.com/wzjbg/p/8516531.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3