How to convert QImage(QPixmap) to PIL Image in Pyt

2019-07-25 12:44发布

问题:

I would like to convert a image from QImage or Qpixmap class to PIL Image. I found this: Convert PyQt to PIL image

But it seems to doesn't work in Python3. Is the way to implement this to Pyhton3 or do it more simply using new approaches exist?

回答1:

According to the docs:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

So the solution is to do the conversion of cStringIO.StringIO to io.BytesIO.

PyQt5:

import io
from PIL import Image
from PyQt5.QtGui import QImage
from PyQt5.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()

PyQt4:

import io
from PIL import Image
from PyQt4.QtGui import QImage
from PyQt4.QtCore import QBuffer

img = QImage("image.png")
buffer = QBuffer()
buffer.open(QBuffer.ReadWrite)
img.save(buffer, "PNG")
pil_im = Image.open(io.BytesIO(buffer.data()))
pil_im.show()