Skip to content

Commit

Permalink
compat.py: Add utility function to get raw bytes from QImages
Browse files Browse the repository at this point in the history
  • Loading branch information
zjp committed Apr 26, 2024
1 parent 3238de7 commit fcd4545
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
12 changes: 12 additions & 0 deletions qtpy/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
PYQT6,
PYSIDE2,
PYSIDE6,
QtBindingsNotFoundError,
)
from .QtWidgets import QFileDialog

Expand Down Expand Up @@ -200,3 +201,14 @@ def isalive(obj):

return shiboken.isValid(obj)
return None


# =============================================================================
def getimagebytes(qimage):
if PYQT5:
return qimage.bits().asstring(qimage.byteCount())
if PYQT6:
return qimage.bits().asstring(qimage.sizeInBytes())
if PYSIDE2 or PYSIDE6:
return qimage.bits().tobytes()
raise QtBindingsNotFoundError
14 changes: 14 additions & 0 deletions qtpy/tests/test_compat.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"""Test the compat module."""

import sys

import pytest

from qtpy import QtWidgets, compat

from qtpy.QtCore import QRectF, QSize, Qt
from qtpy.QtGui import QBrush, QImage, QPainter
from qtpy.tests.utils import not_using_conda


Expand All @@ -22,3 +26,13 @@ def test_isalive(qtbot):
with qtbot.waitSignal(test_widget.destroyed):
test_widget.deleteLater()
assert compat.isalive(test_widget) is False


def test_getimagebytes(qtbot):
"""Test compat.getimagebytes"""
image = QImage(QSize(100, 100), QImage.Format_RGB32)
painter = QPainter(image)
painter.setBrush(QBrush(Qt.black))
painter.fillRect(QRectF(0, 0, 100, 100), Qt.black)
bytes = compat.getimagebytes(image)
assert len(bytes) == 100 * 100 * 4

0 comments on commit fcd4545

Please sign in to comment.