ImageQt.py 6.2 KB

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