简体   繁体   中英

Python - matplotlib - PyQT: Copy image to clipboard

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

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

Any solutions?

You're not creating a valid image.

im = QImage(self.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)

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.

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

Save to clipboard:

QApplication.clipboard().setPixmap(pixmap)

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

when working in an interactive Python shell you can use a function like this

def to_clipboard(fig):
  QApplication.clipboard().setImage(QPixmap.grabWidget(fig.canvas).toImage())
  print('figure %d copied to clipboard' % fig.number)

and then use it like to_clipboard(gcf()) to store the current figure.

In addition to @mata answer, for the update, since QPixmap.grabWidget is now obsolete, we can use:

pixmap = self.canvas.grab()
QApplication.clipboard().setPixmap(pixmap)

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