Last Updated on 2020-10-31 by Clay
Problem
When I using Python PyQt5 module to show image, I got an error message:
ValueError: unsupported image mode 'LA'
Solution
The meaning of this error message is the function I used is not support the LA mode image. I read the source code of function:
# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
if py3:
im = str(im.toUtf8(), "utf-8")
else:
im = unicode(im.toUtf8(), "utf-8") # noqa: F821
if isPath(im):
im = Image.open(im)
if im.mode == "1":
format = QImage.Format_Mono
elif im.mode == "L":
format = QImage.Format_Indexed8
colortable = []
for i in range(256):
colortable.append(rgb(i, i, i))
elif im.mode == "P":
format = QImage.Format_Indexed8
colortable = []
palette = im.getpalette()
for i in range(0, len(palette), 3):
colortable.append(rgb(*palette[i : i + 3]))
elif im.mode == "RGB":
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
try:
data = im.tobytes("raw", "BGRA")
except SystemError:
# workaround for earlier versions
r, g, b, a = im.split()
im = Image.merge("RGBA", (b, g, r, a))
format = QImage.Format_ARGB32
else:
raise ValueError("unsupported image mode %r" % im.mode)
I found it is only support the following image modes:
- 1
- L
- P
- RGB
- RGBA
So I was thinking, it is very likely that I need to manually change the mode of image.
I read the document of Pillow module: https://pillow.readthedocs.io/en/5.1.x/reference/Image.html
Sure enough, there are functions that can be easily converted:
So I loaded the error mode image (LA mode), convert it and save as png format.
image = Image.open('mode.png')
image.convert('RGBA').save('newMode.png')
I loaded it again, this time I never got error message.