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

  • 相关阅读:
    Roles in graphs
    COMMUNITY DETECTION
    jquery官方API
    react打包后引入
    pc网站相互跳转
    动画点击事件
    导入组件
    纯css制作loading效果
    canvas时钟
    canvas实现动画 地球绕太阳公转 月球绕地球公转
  • 原文地址:https://www.cnblogs.com/wzjbg/p/8516531.html
Copyright © 2011-2022 走看看