1. 报错信息
我在使用PIL库创建图像的时候遇到的错误
from PIL import Image,ImageDraw,ImageFont h = 500 w = 500 trans_bg = Image.new("RGBA",(w,h),(255,0,255,0)) trans_bg 上面这段代码出现报错 详细信息如下 OSError: cannot write mode RGBA as JPEG
The above exception was the direct cause of the following exception: 4 except Exception as e: 645 msg = f"Could not save to {image_format} for display" --> 646 raise ValueError(msg) from e 647 return b.getvalue()
ValueError: Could not save to JPEG for display
搜索到的大部分回答是这个错误是由于尝试将RGBA模式的图像保存为JPEG格式而引起的。JPEG格式不支持透明度通道,因此无法保存RGBA图像。
我个人猜测是PIL显示时。是JPEG格式,但是由于JPEG是三通道所以不可以显示四通道图片。
2. 解决方法
使用 matplotlib
来进行显示
# 导入PIL
from PIL import Image,ImageDraw,ImageFont
import matplotlib.pyplot as plt
h = 500
w = 500
# 透明底图
bg = Image.new(mode='RGBA',size=(w,h),color=(255,0,255,0))
# 绘制
img = ImageDraw.Draw(im=bg ,mode='RGBA')
font = ImageFont.truetype('./fonts/MSYH.ttc',40,encoding="utf-8")```
img.text((50,10),"使用PIL创建图层",font=font,fill=(0,0,255,255))
plt.imshow(bg)
此时我要修改bg的一些数据 因此转换成ndarray格式,此外还要copy,否则无法修改数值
import numpy
trans_bg_np = np.asarray(bg)
# 创建一个可写的副本 trans_bg_np是一个只读视图,无法直接修改其中的元素。
trans_bg_np_copy = np.copy(trans_bg_np)
# alpha通道设置
trans_bg_np_copy[:,:,3] = np.where(black_bg==255,0,trans_bg_np_copy[:,:,3])
# 将副本转换回PIL图像
trans_bg_modified = Image.fromarray(trans_bg_np_copy)
# 显示修改后的图像
trans_bg_modified.show()
plt.imshow(trans_bg_modified )