0

I have this PySide2 code which works on Linux with Python 2.7

from PySide2.QtCore import QBuffer, QByteArray

...

image = self.clipboard.image()
ba = QByteArray()
buffer = QBuffer(ba)
buffer.open(QIODevice.WriteOnly)
image.save(buffer, "PNG")
return bytes(buffer.data())

But on windows with Python 3.6 it fails here:

  File "C:\....foo.py", line 93, in image_to_png
    return bytes(buffer.data())

Exception:

TypeError: 'bytes' object cannot be interpreted as an integer

What is the most simple way to get the PNG as bytes?

I would like to avoid to create a temporary file, since it is not needed for this context.

(I use PySide2, but I could switch to a different python-QT binding if you think it makes more sense. Please leave a comment if you think so)

3
  • Are you just converting old code to run on Python 3, or does it need to run on both 2.7 and 3.6? Commented Sep 12, 2018 at 9:46
  • On Python 3.6, what is the type of buffer.data() ? Commented Sep 12, 2018 at 9:48
  • @PM2Ring Up to now the same code base works in 2.7 and 3.6. It would be nice, if this could stay this way (at least for some months). Commented Sep 12, 2018 at 10:15

2 Answers 2

2

Looks like QBuffer.data() return type is QByteArray (which probably cannot be handled by the bytes() constructor), however QByteArray.data() return type is bytes. So, I think you should try return buffer.data().data() instead of return bytes(buffer.data()).

Sign up to request clarification or add additional context in comments.

1 Comment

I think the online documentation is incorrect in this case, since it indicates str as the return type of QByteArray.data(): link
0

This is a work-around.

def image_to_png(image):
    temp_png = tempfile.mktemp('.png')
    image.save(temp_png)
    with io.open(temp_png, 'rb') as fd:
        content = fd.read()
    os.unlink(temp_png)
    return content

If possible, I would like to avoid the temporary file. Other solutions are welcome.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.