近來研究圖片的剪切拼接,用到PIL,在打開PNG格式保存為JPEG格式的圖片發現報錯:
1 import os 2 from PIL import Image 3 4 5 im = Image.open(r'E:\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 = r'E:\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