ImageQt.py 5.8 KB

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