Python - matplotlib - PyQT:将图像复制到剪贴板 [英] Python - matplotlib - PyQT: Copy image to clipboard

查看:248
本文介绍了Python - matplotlib - PyQT:将图像复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把matplotlib的当前图形复制到剪贴板:

I want to copy the current figure of matplotlib to the clipboard:

这段代码不起作用(出于测试目的,我想稍后将位图保存到磁盘,我将把它用作位图图像.我想从拥有一个可以与QT的QImage,QPixmap,QBitmap或其他一些QT类).

this code doens't work(for testing purposes, I want to save the bitmap to disk later on I will use it as a bitmap-image. I want to start with having a memory-bitmap that I can use with the QT's QImage, QPixmap, QBitmap or some other QT-class).

rgba = self.canvas.buffer_rgba()
im = QImage(self.canvas.buffer_rgba())
print(im.depth())   # --> 0
print(im.save('test.gif',r'GIF')) # ---> False

有什么解决办法吗?

推荐答案

您没有创建有效的图像.

You're not creating a valid image.

im = QImage(self.canvas.buffer_rgba())

实际上忽略了您传递的参数.canvas.buffer_rgba() 返回一个内存视图,其中没有任何 可用构造函数可以使用:

actually ignores the argument you're passing. canvas.buffer_rgba() returns a memoryview, which none of the available constructors can work with:

QImage()
QImage(QSize, QImage.Format)
QImage(int, int, QImage.Format)
QImage(str, int, int, QImage.Format)
QImage(sip.voidptr, int, int, QImage.Format)
QImage(str, int, int, int, QImage.Format)
QImage(sip.voidptr, int, int, int, QImage.Format)
QImage(list-of-str)
QImage(QString, str format=None)
QImage(QImage)
QImage(QVariant)

在python中实际上只有一个__init__方法,所以类型检查必须通过内部检查来完成. QImage(QVariant)基本上与 QImage(object)相同(实际上,在python3中,它确实是 ),因此基本上允许您传递任何对象,如果无法在内部将其转换为 QVariant ,则它将被忽略,因此返回的QImage将为空.

In python there is really only one __init__ method, so type checking has to be done by internal checks. QImage(QVariant) is basically the same as QImage(object) (in fact, in python3, that's exactly what it is), so it basically allows you to pass any object, it's just ignored if it can't be converted to a QVariant internally, so the returned QImage will be empty.

如果要从原始rgba数据构建图像,则需要指定其大小,因为无法从原始数据以及格式中获取此信息.这应该起作用:

If you want to construct a image from raw rgba data, you need to specify it's size, as there is no way to get this information from raw data, and also the format. This should work:

size = self.canvas.size()
width, height = size.width(), size.height()
im = QImage(self.canvas.buffer_rgba(), width, height, QImage.Format_ARGB32)
im.save('test.png')

另一种方法是直接将画布作为像素图获取:

Another way would be to grab the canvas directly as a pixmap:

pixmap = QPixmap.grabWidget(self.canvas)
pixmap.save('test.png')

保存到剪贴板:

QApplication.clipboard().setPixmap(pixmap)

哦,你不应该使用gif,使用png.由于它的专有性质,gif 通常不能用作支持的输出格式.检查 QImageWriter.supportedImageFormats().

Oh, and you shouldn't use gif, use png. Due to it's proprietary nature gif is usually not available as supported output format. Check QImageWriter.supportedImageFormats().

这篇关于Python - matplotlib - PyQT:将图像复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆