zoukankan      html  css  js  c++  java
  • PIL PNG格式通道问题的解决方法

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

     1 import os
     2 from PIL import Image
     3 
     4 
     5 im = Image.open(r'E:work	estcrop	esthn1.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	estcrop	esthn2.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

  • 相关阅读:
    DS博客作业05--树
    DS博客作业03--栈和队列
    DS博客作业02--线性表
    DS博客作业01-日期抽象数据类型设计和实现
    easyx的基础应用教程
    C语言博客作业06--结构体&文件
    python接口自动化
    fiddler的使用
    python接口自动化——初级
    python.day.10——面向对象(二)
  • 原文地址:https://www.cnblogs.com/wzjbg/p/8516531.html
Copyright © 2011-2022 走看看