Python 3, plone.api, read (blob) image

When porting to python 3, I run into (another) unicode error.
This works with python 2.7, but in python 3 'return NamedBlobImage' gives error:

*** UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

filename is a string, like: '/Users/me/Plone52/zinstance/src/my.theme/src/my.theme/theme/favicon.png'

from plone import api
import os
from plone.namedfile.file import NamedBlobImage


icon_image.image = load_image(i_image)

def load_image(i_image):
    filename = os.path.join(os.path.dirname(__file__), 'theme',
    return NamedBlobImage(
        data=open(filename, 'r').read(),

Open the file for reading in binary mode, not in text mode

Great, thank.

For later reference:

return NamedBlobImage(
  data=open(filename, 'rb').read(),

Any your code will likely raise a ResourceWarning under Python 3 when you inline open and read the file. Use a context manager or properly open and close the file.

Plone Foundation Code of Conduct