python - 不能在 PIL 库中的 png 文件上使用 Image.putalpha()。操作系统错误 : cannot write mode PA as PNG

标签 python jupyter-notebook python-imaging-library

决定在 jupyter notebook 中尝试 PIL lib。我有一个 png 格式的蓝色图像(没有别的)。
想让它半透明。所以我做了:

from PIL import Image
blue = Image.open("blue_color.png")
当我通过 jupyter 打开图像时,一切都很好。但后来我应用 .putalpha() 方法:
blue.putalpha(128)
得到这个:
KeyError                                  Traceback (most recent call last)
~\Anaconda3\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk)
    799     try:
--> 800         rawmode, mode = _OUTMODES[mode]
    801     except KeyError:

KeyError: 'PA'

During handling of the above exception, another exception occurred:

OSError                                   Traceback (most recent call last)
~\Anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj)
    343             method = get_real_method(obj, self.print_method)
    344             if method is not None:
--> 345                 return method()
    346             return None
    347         else:

~\Anaconda3\lib\site-packages\PIL\Image.py in _repr_png_(self)
    698         """
    699         b = io.BytesIO()
--> 700         self.save(b, "PNG")
    701         return b.getvalue()
    702 

~\Anaconda3\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
   2082 
   2083         try:
-> 2084             save_handler(self, fp, filename)
   2085         finally:
   2086             # do what we can to clean up

~\Anaconda3\lib\site-packages\PIL\PngImagePlugin.py in _save(im, fp, filename, chunk)
    800         rawmode, mode = _OUTMODES[mode]
    801     except KeyError:
--> 802         raise IOError("cannot write mode %s as PNG" % mode)
    803 
    804     #

OSError: cannot write mode PA as PNG
对另一个颜色文件进行了相同的操作,但它是 jpg 格式。一切都很好!
是文件格式问题吗?谁能告诉我如何解决这个问题?
提前致谢!

最佳答案

您可以先将 png 转换为 jpg。

im = Image.open("blue_color.png")
rgb_im = im.convert('RGB')
rgb_im.save('blue_color.jpg')

关于python - 不能在 PIL 库中的 png 文件上使用 Image.putalpha()。操作系统错误 : cannot write mode PA as PNG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62780080/

相关文章:

python - 关于postgresql序列的问题

python - 具有多个 iPyWidgets 下拉菜单的交互式 Covid 绘图

python - 从具有任意数量像素分量的图像中读取数据的有效方法是什么? ( python ,太平船务)

python - PIL的色彩空间转换YCbCr -> RGB

python - 使用变量作为 python 的切片索引

从关系数据库构造类的 Python 库? (反向ORM)

python - 检查当前方法是否已在特定方法中执行的最pythonic方法是什么?

python - ipython 笔记本中的中心对齐输出

Python argparse 错误 : error: argument count: invalid int value

python - 用于图像验证的 PIL 或 imghdr