ImageQt.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # a simple Qt image interface.
  6. #
  7. # history:
  8. # 2006-06-03 fl: created
  9. # 2006-06-04 fl: inherit from QImage instead of wrapping it
  10. # 2006-06-05 fl: removed toimage helper; move string support to ImageQt
  11. # 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
  12. #
  13. # Copyright (c) 2006 by Secret Labs AB
  14. # Copyright (c) 2006 by Fredrik Lundh
  15. #
  16. # See the README file for information on usage and redistribution.
  17. #
  18. from __future__ import annotations
  19. __lazy_modules__ = {"PIL._util", "io"}
  20. import sys
  21. from io import BytesIO
  22. from . import Image
  23. from ._deprecate import deprecate
  24. from ._util import is_path
  25. TYPE_CHECKING = False
  26. if TYPE_CHECKING:
  27. from collections.abc import Callable
  28. from typing import Any
  29. from . import ImageFile
  30. QBuffer: type
  31. qt_version: str | None
  32. qt_versions = [
  33. ["6", "PyQt6"],
  34. ["side6", "PySide6"],
  35. ]
  36. # If a version has already been imported, attempt it first
  37. qt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)
  38. for version, qt_module in qt_versions:
  39. try:
  40. qRgba: Callable[[int, int, int, int], int]
  41. if qt_module == "PyQt6":
  42. from PyQt6.QtCore import QBuffer, QByteArray, QIODevice
  43. from PyQt6.QtGui import QImage, QPixmap, qRgba
  44. elif qt_module == "PySide6":
  45. from PySide6.QtCore import ( # type: ignore[assignment]
  46. QBuffer,
  47. QByteArray,
  48. QIODevice,
  49. )
  50. from PySide6.QtGui import QImage, QPixmap, qRgba # type: ignore[assignment]
  51. except (ImportError, RuntimeError):
  52. continue
  53. qt_is_installed = True
  54. qt_version = version
  55. break
  56. else:
  57. qt_is_installed = False
  58. qt_version = None
  59. def rgb(r: int, g: int, b: int, a: int = 255) -> int:
  60. """(Internal) Turns an RGB color into a Qt compatible color integer."""
  61. # use qRgb to pack the colors, and then turn the resulting long
  62. # into a negative integer with the same bitpattern.
  63. return qRgba(r, g, b, a) & 0xFFFFFFFF
  64. def fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:
  65. """
  66. :param im: QImage or PIL ImageQt object
  67. """
  68. buffer = QBuffer()
  69. qt_openmode: object
  70. if qt_version == "6":
  71. try:
  72. qt_openmode = getattr(QIODevice, "OpenModeFlag")
  73. except AttributeError:
  74. qt_openmode = getattr(QIODevice, "OpenMode")
  75. else:
  76. qt_openmode = QIODevice
  77. buffer.open(getattr(qt_openmode, "ReadWrite"))
  78. # preserve alpha channel with png
  79. # otherwise ppm is more friendly with Image.open
  80. if im.hasAlphaChannel():
  81. im.save(buffer, "png")
  82. else:
  83. im.save(buffer, "ppm")
  84. b = BytesIO()
  85. b.write(buffer.data())
  86. buffer.close()
  87. b.seek(0)
  88. return Image.open(b)
  89. def fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:
  90. return fromqimage(im)
  91. def align8to32(bytes: bytes, width: int, mode: str) -> bytes:
  92. """
  93. converts each scanline of data from 8 bit to 32 bit aligned
  94. """
  95. deprecate("ImageQt.align8to32", 14)
  96. bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]
  97. # calculate bytes per line and the extra padding if needed
  98. bits_per_line = bits_per_pixel * width
  99. full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
  100. bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
  101. extra_padding = -bytes_per_line % 4
  102. # already 32 bit aligned by luck
  103. if not extra_padding:
  104. return bytes
  105. new_data = [
  106. bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding
  107. for i in range(len(bytes) // bytes_per_line)
  108. ]
  109. return b"".join(new_data)
  110. def _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:
  111. data = None
  112. colortable = None
  113. exclusive_fp = False
  114. # handle filename, if given instead of image name
  115. if hasattr(im, "toUtf8"):
  116. # FIXME - is this really the best way to do this?
  117. im = str(im.toUtf8(), "utf-8")
  118. if is_path(im):
  119. im = Image.open(im)
  120. exclusive_fp = True
  121. assert isinstance(im, Image.Image)
  122. qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage
  123. if im.mode == "1":
  124. format = getattr(qt_format, "Format_Mono")
  125. elif im.mode == "L":
  126. format = getattr(qt_format, "Format_Indexed8")
  127. colortable = [rgb(i, i, i) for i in range(256)]
  128. elif im.mode == "P":
  129. format = getattr(qt_format, "Format_Indexed8")
  130. palette = im.getpalette()
  131. assert palette is not None
  132. colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]
  133. elif im.mode == "RGB":
  134. # Populate the 4th channel with 255
  135. im = im.convert("RGBA")
  136. data = im.tobytes("raw", "BGRA")
  137. format = getattr(qt_format, "Format_RGB32")
  138. elif im.mode == "RGBA":
  139. data = im.tobytes("raw", "BGRA")
  140. format = getattr(qt_format, "Format_ARGB32")
  141. elif im.mode == "I;16":
  142. im = im.point(lambda i: i * 256)
  143. format = getattr(qt_format, "Format_Grayscale16")
  144. else:
  145. if exclusive_fp:
  146. im.close()
  147. msg = f"unsupported image mode {repr(im.mode)}"
  148. raise ValueError(msg)
  149. size = im.size
  150. if data is None:
  151. # Compute the stride (scanline size) in bytes when aligned
  152. # to Qt's requirement that scanlines be aligned to 32 bits.
  153. bpp = {"1": 1, "L": 8, "P": 8, "I;16": 16}[im.mode]
  154. stride = (bpp * size[0] + 31) // 32 * (32 // 8)
  155. data = im.tobytes("raw", im.mode, stride)
  156. if exclusive_fp:
  157. im.close()
  158. return {"data": data, "size": size, "format": format, "colortable": colortable}
  159. if qt_is_installed:
  160. class ImageQt(QImage):
  161. def __init__(self, im: Image.Image | str | QByteArray) -> None:
  162. """
  163. An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
  164. class.
  165. :param im: A PIL Image object, or a file name (given either as
  166. Python string or a PyQt string object).
  167. """
  168. im_data = _toqclass_helper(im)
  169. # must keep a reference, or Qt will crash!
  170. # All QImage constructors that take data operate on an existing
  171. # buffer, so this buffer has to hang on for the life of the image.
  172. # Fixes https://github.com/python-pillow/Pillow/issues/1370
  173. self.__data = im_data["data"]
  174. super().__init__(
  175. self.__data,
  176. im_data["size"][0],
  177. im_data["size"][1],
  178. im_data["format"],
  179. )
  180. if im_data["colortable"]:
  181. self.setColorTable(im_data["colortable"])
  182. def toqimage(im: Image.Image | str | QByteArray) -> ImageQt:
  183. return ImageQt(im)
  184. def toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:
  185. qimage = toqimage(im)
  186. pixmap = getattr(QPixmap, "fromImage")(qimage)
  187. if qt_version == "6":
  188. pixmap.detach()
  189. return pixmap