1

Can PIL open an image using pyqt4 resource file?

from PIL import Image, ImageWin
import res_rc #resource file

image = Image.open(":/images/image.png")
dim = ImageWin.Dib(image)

I'm getting this error

IOError: [Errno 22] invalid mode ('rb') or filename :/images/image.png'

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
unice
  • 2,655
  • 5
  • 43
  • 78
  • Can you get a file-like to the resource data? – Ignacio Vazquez-Abrams Dec 13 '12 at 01:30
  • I don't know either. If possible I just want to put the image to the pyqt4 resource file rather than separating it to an image file. So the user cannot edit or erase the image file. – unice Dec 13 '12 at 01:44
  • It's pretty easy if you can get a file-like, so work on that first. – Ignacio Vazquez-Abrams Dec 13 '12 at 01:52
  • Do you literally mean from the resource file, or do you mean from the resource object code ? If the former, it is a simply matter of parsing a XML file. If the latter, you have access to PyQt modules, so load the resource using `QPixMap` and convert it to use with PIL. – mmgp Dec 13 '12 at 16:48

1 Answers1

2

To read an image file from a resource, open it with a QFile and pass the raw data to a file-like object that can be used by PIL:

from PyQt4.QtCore import QFile
from cStringIO import StringIO
from PIL import Image, ImageWin
import res_rc

stream = QFile(':/images/image.png')
if stream.open(QFile.ReadOnly):
    data = stream.readAll()
    stream.close()
    image = Image.open(StringIO(data))
    dim = ImageWin.Dib(image)

Note that resources are designed to be compiled into the application, and so they are strictly read-only.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336