Skip to content

[已解決][Python] ValueError: unsupported image mode ‘LA’

在使用 Python 當中的 PyQt5 來製作能顯示圖片的時候,我曾經遇到以下這個報錯:

ValueError: unsupported image mode 'LA'

順帶一提,這是在我進行《PyInstaller 可發布並夾帶圖片的方法》時遇到的問題,若有興趣,不妨前往看看。


解決方法

這個報錯的意思,是在告訴我這個 function 並不支援 “LA” 這個模式的圖片。我去看了我讀取圖片的 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)



研究了一下,發現這個 function 基本上只支援:

  • 1
  • L
  • P
  • RGB
  • RGBA

以上這五種模式,那麼我們要做的事情就很單純了:我們要改變圖片的模式。

我前往了 Pillow 的 document查看: https://pillow.readthedocs.io/en/5.1.x/reference/Image.html

果不其然,有簡單可以轉換的辦法:

於是我將原本報錯的圖片讀取進來,轉換格式之後再次存檔。

image = Image.open('mode.png')
image.convert('RGBA').save('newMode.png')

讀取新的圖片,這次就沒有報錯,可以正常打開了。

Tags:

Leave a Reply