Skip to content

Image

Qt Base Class: QImage

Signature: QImage(self) -> None QImage(self, arg__1: str, arg__2: int, arg__3: int, arg__4: PySide6.QtGui.QImage.Format) -> None QImage(self, arg__1: str, arg__2: int, arg__3: int, arg__4: int, arg__5: PySide6.QtGui.QImage.Format) -> None QImage(self, arg__1: Union[PySide6.QtGui.QImage, str]) -> None QImage(self, data: bytes, width: int, height: int, bytesPerLine: int, format: PySide6.QtGui.QImage.Format, cleanupFunction: Optional[Callable] = None, cleanupInfo: Optional[int] = None) -> None QImage(self, data: bytes, width: int, height: int, format: PySide6.QtGui.QImage.Format, cleanupFunction: Optional[Callable] = None, cleanupInfo: Optional[int] = None) -> None QImage(self, fileName: Union[str, bytes, os.PathLike], format: Optional[bytes] = None) -> None QImage(self, size: PySide6.QtCore.QSize, format: PySide6.QtGui.QImage.Format) -> None QImage(self, width: int, height: int, format: PySide6.QtGui.QImage.Format) -> None QImage(self, xpm: Iterable) -> None

Base classes

Name Children Inherits
SerializeMixin
prettyqt.utils.serializemixin
PaintDeviceMixin
prettyqt.gui.paintdevice
QImage
PySide6.QtGui
QImage(self) -> None

⋔ Inheritance diagram

graph TD
  1473245530912["gui.Image"]
  1473299806240["utils.SerializeMixin"]
  140713234304496["builtins.object"]
  1473245548480["gui.PaintDeviceMixin"]
  1473299972080["QtGui.QImage"]
  1473300082368["QtGui.QPaintDevice"]
  1473291690208["Shiboken.Object"]
  1473299806240 --> 1473245530912
  140713234304496 --> 1473299806240
  1473245548480 --> 1473245530912
  140713234304496 --> 1473245548480
  1473299972080 --> 1473245530912
  1473300082368 --> 1473299972080
  1473291690208 --> 1473300082368
  140713234304496 --> 1473291690208

🛈 DocStrings

Bases: SerializeMixin, PaintDeviceMixin, QImage

Hardware-independent image representation with direct access to the pixel data.

Source code in prettyqt\gui\image.py
class Image(serializemixin.SerializeMixin, gui.PaintDeviceMixin, gui.QImage):
    """Hardware-independent image representation with direct access to the pixel data."""

    def __setitem__(self, index: tuple[int, int], value):
        self.setPixel(index[0], index[1], value)

    def __getitem__(self, index: tuple[int, int]) -> int | list[int]:
        match index:
            case int() as row, int() as col:
                return self.pixel(row, col)
            case (row, col):
                rowcount = self.height()
                colcount = self.width()
                return [
                    self.pixel(i, j)
                    for i, j in helpers.iter_positions(row, col, rowcount, colcount)
                ]
            case _:
                raise TypeError(index)

    @classmethod
    def from_ndarray(cls, arr) -> Self:
        import numpy as np

        height, width, bytes_per_component = arr.shape
        if arr.dtype in {np.float32, np.float64}:
            arr = (255 * arr).round()
        arr = arr.astype(np.uint8)
        return cls(
            arr.data,
            width,
            height,
            bytes_per_component * width,
            gui.QImage.Format.Format_RGB888,
        )

    def to_ndarray(
        self, fmt: FormatStr | gui.QImage.Format = "rgb888", channels: int = 3
    ):
        import numpy as np

        qimage = self.convert_to_format(fmt)
        width = qimage.width()
        height = qimage.height()

        ptr = qimage.constBits()
        array = np.array(ptr).reshape(height, width, channels)  # Copies the data
        return array

    @classmethod
    def from_pil(cls, image) -> Self:
        # from https://github.com/python-pillow/Pillow/blob/main/src/PIL/ImageQt.py
        from PIL import ImageQt

        data = ImageQt._toqclass_helper(image)
        img = cls(data["data"], data["size"][0], data["size"][1], data["format"])
        if data["colortable"]:
            img.setColorTable(data["colortable"])
        img.__data = data["data"]
        return img

    @classmethod
    def for_mimetype(cls, path: os.PathLike) -> Self | None:
        """Try to create an icon from theme using the file mimetype.

        E.g.::

            return self.mimetype_icon(
                path, fallback=':/icons/text-x-python.png')

        :param path: file path for which the icon must be created
        :param fallback: fallback icon path (qrc or file system)
        :returns: QIcon or None if the file mimetype icon could not be found.
        """
        path = os.fspath(path)
        if mime := mimetypes.guess_type(path)[0]:
            icon = mime.replace("/", "-")
            # if system.WINDOWS:
            #     return icons.file()
            if cls.hasThemeIcon(icon):
                icon = cls(cls.fromTheme(icon))
                if not icon.isNull():
                    return icon
        return None  #  gui.Icon.fromTheme("text-x-generic")

    def to_pil(self):
        from PIL import Image as PILImage

        buffer = core.Buffer()
        buffer.open(core.Buffer.OpenModeFlag.ReadWrite)
        self.save(buffer, "PNG")
        return PILImage.open(io.BytesIO(buffer.data()))

    def invert_pixels(self, invert_alpha: bool = False):
        self.invertPixels(
            gui.QImage.InvertMode.InvertRgba
            if invert_alpha
            else gui.QImage.InvertMode.InvertRgb
        )

    def convert_to_format(self, fmt: FormatStr | gui.QImage.Format) -> Self:
        return type(self)(self.convertToFormat(FORMAT.get_enum_value(fmt)))

    def as_bytes(self) -> bytes:
        bits = self.bits()
        if bits is None:
            return b""
        match API:
            case "pyqt6":
                return bits.asstring(self.sizeInBytes())
            case "pyside6":
                return bits.tobytes()

for_mimetype(path: os.PathLike) -> Self | None classmethod

Try to create an icon from theme using the file mimetype.

E.g.::

return self.mimetype_icon(
    path, fallback=':/icons/text-x-python.png')

:param path: file path for which the icon must be created :param fallback: fallback icon path (qrc or file system) :returns: QIcon or None if the file mimetype icon could not be found.

Source code in prettyqt\gui\image.py
@classmethod
def for_mimetype(cls, path: os.PathLike) -> Self | None:
    """Try to create an icon from theme using the file mimetype.

    E.g.::

        return self.mimetype_icon(
            path, fallback=':/icons/text-x-python.png')

    :param path: file path for which the icon must be created
    :param fallback: fallback icon path (qrc or file system)
    :returns: QIcon or None if the file mimetype icon could not be found.
    """
    path = os.fspath(path)
    if mime := mimetypes.guess_type(path)[0]:
        icon = mime.replace("/", "-")
        # if system.WINDOWS:
        #     return icons.file()
        if cls.hasThemeIcon(icon):
            icon = cls(cls.fromTheme(icon))
            if not icon.isNull():
                return icon
    return None  #  gui.Icon.fromTheme("text-x-generic")