Pillow/src/PIL/ImageQt.py

196 lines
5.7 KiB
Python
Raw Normal View History

2010-07-31 06:52:47 +04:00
#
# The Python Imaging Library.
# $Id$
#
# a simple Qt image interface.
#
# history:
# 2006-06-03 fl: created
# 2006-06-04 fl: inherit from QImage instead of wrapping it
# 2006-06-05 fl: removed toimage helper; move string support to ImageQt
2013-11-13 15:34:09 +04:00
# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)
2010-07-31 06:52:47 +04:00
#
# Copyright (c) 2006 by Secret Labs AB
# Copyright (c) 2006 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
import sys
from io import BytesIO
from . import Image
2019-09-26 15:12:28 +03:00
from ._util import isPath
2010-07-31 06:52:47 +04:00
2019-09-26 21:38:19 +03:00
qt_versions = [["5", "PyQt5"], ["side2", "PySide2"]]
# If a version has already been imported, attempt it first
2019-03-21 16:28:20 +03:00
qt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True)
for qt_version, qt_module in qt_versions:
try:
2019-03-21 16:28:20 +03:00
if qt_module == "PyQt5":
from PyQt5.QtGui import QImage, qRgba, QPixmap
from PyQt5.QtCore import QBuffer, QIODevice
2019-03-21 16:28:20 +03:00
elif qt_module == "PySide2":
2018-08-03 16:07:19 +03:00
from PySide2.QtGui import QImage, qRgba, QPixmap
from PySide2.QtCore import QBuffer, QIODevice
except (ImportError, RuntimeError):
continue
qt_is_installed = True
break
else:
qt_is_installed = False
qt_version = None
2010-07-31 06:52:47 +04:00
2015-04-24 02:26:52 +03:00
def rgb(r, g, b, a=255):
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
2010-07-31 06:52:47 +04:00
# use qRgb to pack the colors, and then turn the resulting long
# into a negative integer with the same bitpattern.
2019-03-21 16:28:20 +03:00
return qRgba(r, g, b, a) & 0xFFFFFFFF
2010-07-31 06:52:47 +04:00
def fromqimage(im):
2016-09-24 12:10:46 +03:00
"""
:param im: A PIL Image object, or a file name
(given either as Python string or a PyQt string object)
"""
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
# preserve alpha channel with png
# otherwise ppm is more friendly with Image.open
if im.hasAlphaChannel():
2019-03-21 16:28:20 +03:00
im.save(buffer, "png")
else:
2019-03-21 16:28:20 +03:00
im.save(buffer, "ppm")
2015-06-21 09:31:51 +03:00
b = BytesIO()
2019-10-07 15:34:12 +03:00
b.write(buffer.data())
buffer.close()
2015-06-21 09:31:51 +03:00
b.seek(0)
2015-11-30 14:06:18 +03:00
return Image.open(b)
def fromqpixmap(im):
return fromqimage(im)
# buffer = QBuffer()
# buffer.open(QIODevice.ReadWrite)
# # im.save(buffer)
# # What if png doesn't support some image features like animation?
# im.save(buffer, 'ppm')
# bytes_io = BytesIO()
# bytes_io.write(buffer.data())
# buffer.close()
# bytes_io.seek(0)
2015-11-30 14:06:18 +03:00
# return Image.open(bytes_io)
2015-12-10 01:35:35 +03:00
def align8to32(bytes, width, mode):
"""
converts each scanline of data from 8 bit to 32 bit aligned
"""
2019-03-21 16:28:20 +03:00
bits_per_pixel = {"1": 1, "L": 8, "P": 8}[mode]
# calculate bytes per line and the extra padding if needed
bits_per_line = bits_per_pixel * width
full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
extra_padding = -bytes_per_line % 4
# already 32 bit aligned by luck
if not extra_padding:
return bytes
new_data = []
2015-09-30 08:28:42 +03:00
for i in range(len(bytes) // bytes_per_line):
2019-03-21 16:28:20 +03:00
new_data.append(
bytes[i * bytes_per_line : (i + 1) * bytes_per_line]
+ b"\x00" * extra_padding
)
2019-03-21 16:28:20 +03:00
return b"".join(new_data)
2015-12-10 01:35:35 +03:00
def _toqclass_helper(im):
data = None
colortable = None
# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
2019-09-26 15:12:28 +03:00
im = str(im.toUtf8(), "utf-8")
if isPath(im):
2015-11-30 14:06:18 +03:00
im = Image.open(im)
if im.mode == "1":
format = QImage.Format_Mono
elif im.mode == "L":
format = QImage.Format_Indexed8
colortable = []
for i in range(256):
colortable.append(rgb(i, i, i))
elif im.mode == "P":
format = QImage.Format_Indexed8
colortable = []
palette = im.getpalette()
for i in range(0, len(palette), 3):
2019-03-21 16:28:20 +03:00
colortable.append(rgb(*palette[i : i + 3]))
elif im.mode == "RGB":
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
data = im.tobytes("raw", "BGRA")
format = QImage.Format_ARGB32
else:
raise ValueError("unsupported image mode %r" % im.mode)
__data = data or align8to32(im.tobytes(), im.size[0], im.mode)
2019-03-21 16:28:20 +03:00
return {"data": __data, "im": im, "format": format, "colortable": colortable}
2018-03-03 12:54:00 +03:00
if qt_is_installed:
2019-03-21 16:28:20 +03:00
class ImageQt(QImage):
def __init__(self, im):
2016-09-24 12:10:46 +03:00
"""
An PIL image wrapper for Qt. This is a subclass of PyQt's QImage
class.
2018-10-21 10:26:08 +03:00
:param im: A PIL Image object, or a file name (given either as
Python string or a PyQt string object).
2016-09-24 12:10:46 +03:00
"""
im_data = _toqclass_helper(im)
# must keep a reference, or Qt will crash!
# All QImage constructors that take data operate on an existing
# buffer, so this buffer has to hang on for the life of the image.
# Fixes https://github.com/python-pillow/Pillow/issues/1370
2019-03-21 16:28:20 +03:00
self.__data = im_data["data"]
super().__init__(
2019-03-21 16:28:20 +03:00
self.__data,
im_data["im"].size[0],
im_data["im"].size[1],
im_data["format"],
)
if im_data["colortable"]:
self.setColorTable(im_data["colortable"])
2015-06-19 08:35:56 +03:00
def toqimage(im):
return ImageQt(im)
def toqpixmap(im):
2015-06-21 09:31:51 +03:00
# # This doesn't work. For now using a dumb approach.
2015-06-19 08:35:56 +03:00
# im_data = _toqclass_helper(im)
# result = QPixmap(im_data['im'].size[0], im_data['im'].size[1])
# result.loadFromData(im_data['data'])
# Fix some strange bug that causes
2019-03-21 16:28:20 +03:00
if im.mode == "RGB":
im = im.convert("RGBA")
2015-06-21 09:31:51 +03:00
2015-06-19 08:35:56 +03:00
qimage = toqimage(im)
2015-06-19 08:36:23 +03:00
return QPixmap.fromImage(qimage)