ImageQt.py 6.2 KB

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