简体   繁体   中英

How to convert QImage(QPixmap) to PIL Image in Python 3?

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM