无法使用Alpha保存JPG图像

时间:2019-08-19 16:03:38

标签: python python-imaging-library

width, height = resized_image.size
dummyImg = np.zeros([height, width, 4], dtype=np.uint8)
for x in range(width):
    for y in range(height):
        color = seg_map[y,x]
        (r,g,b) = resized_image.getpixel((x,y))
        if color == 0:
            dummyImg[y,x] = [255,255,255,255]
        else:
            dummyImg[y,x] = [r,g,b,255]
img = Image.fromarray(dummyImg)
outputFilePath = '15d09a689ca0d4 Mod.jpg'
img.save(outputFilePath)

您好,尝试将图片另存为“ JPG”时出现此错误,我在dummyimg中包含了alpha通道。

Traceback (most recent call last):
  File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 620, in _save
    rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/timmy/Desktop/image-background-removal-master/impr.py", line 79, in <module>
    img.save(outputFilePath)
  File "/home/timmy/.local/lib/python3.6/site-packages/PIL/Image.py", line 2007, in save
    save_handler(self, fp, filename)
  File "/home/timmy/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 622, in _save
    raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode RGBA as JPEG

我检查了GitHub问题cannot write mode RGBA as JPEG (4.2.0) ,他们说它已解决,现在可以解决

1 个答案:

答案 0 :(得分:1)

JPEG文件格式不能处理透明度。要保存具有颜色和透明度的图像,您需要使用其他格式(例如PNG)。

仅当放置alpha通道并使所有像素不透明时,才能保存为JPEG。