如何在Python 3中将QImage(QPixmap)转换为PIL图像?(How to convert QImage(QPixmap) to PIL Image in Python 3?)

编程入门 行业动态 更新时间:2024-10-14 14:15:25
如何在Python 3中将QImage(QPixmap)转换为PIL图像?(How to convert QImage(QPixmap) to PIL Image in Python 3?)

我想将图像从QImage或Qpixmap类转换为PIL图像。 我发现这个: 将PyQt转换为PIL图像

但它似乎在Python3中不起作用。 Pyhton3的实现方式还是更简单地使用新方法?

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?

最满意答案

根据文档 :

StringIO和cStringIO模块消失了。 相反,导入io模块并分别为文本和数据使用io.StringIO或io.BytesIO。

所以解决方案是将cStringIO.StringIO转换为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()

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

更多推荐

本文发布于:2023-08-06 20:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455079.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   图像   如何在   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!