add functions to convert: Image <-> QImage; Image <-> QPixmap (see #897)

This commit is contained in:
Roman Inflianskas 2014-09-15 22:24:56 +04:00 committed by Andrew Murray
parent a09da242fd
commit 2d706d74dc
7 changed files with 275 additions and 81 deletions

View File

@ -101,12 +101,13 @@ except ImportError:
import __builtin__
builtins = __builtin__
from PIL import ImageMode
from PIL import ImageMode, ImageQt
from PIL._binary import i8
from PIL._util import isPath
from PIL._util import isStringType
from PIL._util import deferred_error
import os
import sys
import io
@ -1936,6 +1937,14 @@ class Image(object):
im = self.im.effect_spread(distance)
return self._new(im)
if ImageQt.qt_is_installed:
def toqimage(self):
return ImageQt.toqimage(self)
def toqpixmap(self):
return ImageQt.toqpixmap(self)
# --------------------------------------------------------------------
# Lazy operations
@ -2185,6 +2194,11 @@ def fromarray(obj, mode=None):
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
if ImageQt.qt_is_installed:
from PIL.ImageQt import fromqimage, fromqpixmap
_fromarray_typemap = {
# (shape, typestr) => mode, rawmode
# first two members of shape are set to one

View File

@ -16,87 +16,133 @@
# See the README file for information on usage and redistribution.
#
from PIL import Image
import PIL
from PIL._util import isPath
import sys
if 'PyQt4.QtGui' not in sys.modules:
try:
from PyQt5.QtGui import QImage, qRgba
except:
try:
from PyQt4.QtGui import QImage, qRgba
except:
from PySide.QtGui import QImage, qRgba
qt_is_installed = True
try:
from PyQt5.QtGui import QGuiApplication, QImage, qRgb, qRgba, QPixmap
from PyQt5.QtCore import QBuffer, QIODevice
except ImportError:
try:
from PyQt4.QtGui import QGuiApplication, QImage, qRgb, qRgba, QPixmap
from PyQt4.QtCore import QBuffer, QIODevice
except ImportError:
try:
from PySide.QtGui import QGuiApplication, QImage, qRgb, qRgba, QPixmap
from PySide.QtCore import QBuffer, QIODevice
except ImportError:
qt_is_installed = False
else: #PyQt4 is used
from PyQt4.QtGui import QImage, qRgba
##
# (Internal) Turns an RGB color into a Qt compatible color integer.
from io import BytesIO
def rgb(r, g, b, a=255):
"""(Internal) Turns an RGB color into a Qt compatible color integer."""
# use qRgb to pack the colors, and then turn the resulting long
# into a negative integer with the same bitpattern.
return (qRgba(r, g, b, a) & 0xffffffff)
##
# An PIL image wrapper for Qt. This is a subclass of PyQt4's QImage
# class.
#
# @param im A PIL Image object, or a file name (given either as Python
# string or a PyQt string object).
# :param im A PIL Image object, or a file name (given either as Python string or a PyQt string object).
class ImageQt(QImage):
def fromqimage(im):
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
im.save(buffer, 'ppm')
bytes_io = BytesIO()
try:
bytes_io.write(buffer.data())
except TypeError:
# workaround for Python 2
bytes_io.write(str(buffer.data()))
buffer.close()
bytes_io.seek(0)
return PIL.Image.open(bytes_io)
def __init__(self, im):
data = None
colortable = None
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)
# return PIL.Image.open(bytes_io)
# handle filename, if given instead of image name
if hasattr(im, "toUtf8"):
# FIXME - is this really the best way to do this?
if str is bytes:
im = unicode(im.toUtf8(), "utf-8")
else:
im = str(im.toUtf8(), "utf-8")
if isPath(im):
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):
colortable.append(rgb(*palette[i:i+3]))
elif im.mode == "RGB":
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
try:
data = im.tobytes("raw", "BGRA")
except SystemError:
# workaround for earlier versions
r, g, b, a = im.split()
im = Image.merge("RGBA", (b, g, r, a))
format = QImage.Format_ARGB32
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?
if str is bytes:
im = unicode(im.toUtf8(), "utf-8")
else:
raise ValueError("unsupported image mode %r" % im.mode)
im = str(im.toUtf8(), "utf-8")
if isPath(im):
im = PIL.Image.open(im)
# must keep a reference, or Qt will crash!
self.__data = data or im.tobytes()
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):
colortable.append(rgb(*palette[i:i+3]))
elif im.mode == "RGB":
data = im.tobytes("raw", "BGRX")
format = QImage.Format_RGB32
elif im.mode == "RGBA":
try:
data = im.tobytes("raw", "BGRA")
except SystemError:
# workaround for earlier versions
r, g, b, a = im.split()
im = PIL.Image.merge("RGBA", (b, g, r, a))
format = QImage.Format_ARGB32
else:
raise ValueError("unsupported image mode %r" % im.mode)
QImage.__init__(self, self.__data, im.size[0], im.size[1], format)
# must keep a reference, or Qt will crash!
__data = data or im.tobytes()
return {
'data': __data, 'im': im, 'format': format, 'colortable': colortable
}
if colortable:
self.setColorTable(colortable)
def toqimage(im):
im_data = _toqclass_helper(im)
result = QImage(
im_data['data'], im_data['im'].size[0], im_data['im'].size[1],
im_data['format']
)
if im_data['colortable']:
result.setColorTable(im_data['colortable'])
return result
def toqpixmap(im):
# This doesn't work. For now using a dumb approach.
# 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
if im.mode == 'RGB':
im = im.convert('RGBA')
qimage = im.toqimage()
qimage.save('/tmp/hopper_{}_qpixmap_qimage.png'.format(im.mode))
return QPixmap.fromImage(qimage)

View File

@ -0,0 +1,36 @@
from helper import unittest, PillowTestCase, hopper, image
from test_imageqt import PillowQtTestCase
from PIL import Image, ImageQt
if ImageQt.qt_is_installed:
from PIL.ImageQt import QImage
class TestFromQImage(PillowQtTestCase, PillowTestCase):
def roundtrip(self, expected):
result = Image.fromqimage(expected.toqimage())
# Qt saves all images as rgb
self.assert_image_equal(result, expected.convert('RGB'))
def test_sanity_1(self):
self.roundtrip(hopper('1'))
def test_sanity_rgb(self):
self.roundtrip(hopper('RGB'))
def test_sanity_rgba(self):
self.roundtrip(hopper('RGBA'))
def test_sanity_l(self):
self.roundtrip(hopper('L'))
def test_sanity_p(self):
self.roundtrip(hopper('P'))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,36 @@
from helper import unittest, PillowTestCase, hopper
from test_imageqt import PillowQPixmapTestCase
from PIL import Image, ImageQt
if ImageQt.qt_is_installed:
from PIL.ImageQt import QPixmap
class TestFromQPixmap(PillowQPixmapTestCase, PillowTestCase):
def roundtrip(self, expected):
result = Image.fromqpixmap(expected.toqpixmap())
# Qt saves all pixmaps as rgb
self.assert_image_equal(result, expected.convert('RGB'))
def test_sanity_1(self):
self.roundtrip(hopper('1'))
def test_sanity_rgb(self):
self.roundtrip(hopper('RGB'))
def test_sanity_rgba(self):
self.roundtrip(hopper('RGBA'))
def test_sanity_l(self):
self.roundtrip(hopper('L'))
def test_sanity_p(self):
self.roundtrip(hopper('P'))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,24 @@
from helper import unittest, PillowTestCase, hopper
from test_imageqt import PillowQtTestCase
from PIL import ImageQt
if ImageQt.qt_is_installed:
from PIL.ImageQt import QImage
class TestToQImage(PillowQtTestCase, PillowTestCase):
def test_sanity(self):
for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
data = ImageQt.toqimage(hopper(mode))
data.save('/tmp/hopper_{}_qimage.png'.format(mode))
self.assertTrue(isinstance(data, QImage))
self.assertFalse(data.isNull())
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,25 @@
from helper import unittest, PillowTestCase, hopper
from test_imageqt import PillowQPixmapTestCase
from PIL import ImageQt
if ImageQt.qt_is_installed:
from PIL.ImageQt import QPixmap
class TestToQPixmap(PillowQPixmapTestCase, PillowTestCase):
def test_sanity(self):
QPixmap('Tests/images/hopper.ppm').save(
'/tmp/hopper_RGB_qpixmap_file.png')
for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
data = ImageQt.toqpixmap(hopper(mode))
data.save('/tmp/hopper_{}_qpixmap.png'.format(mode))
self.assertTrue(isinstance(data, QPixmap))
self.assertFalse(data.isNull())
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,20 +1,19 @@
from helper import unittest, PillowTestCase, hopper
try:
from PIL import ImageQt
from PyQt5.QtGui import QImage, qRgb, qRgba
except:
try:
from PyQt4.QtGui import QImage, qRgb, qRgba
except:
try:
from PySide.QtGui import QImage, qRgb, qRgba
except:
# Will be skipped in setUp
pass
from PIL import ImageQt
class TestImageQt(PillowTestCase):
if ImageQt.qt_is_installed:
from PIL.ImageQt import QGuiApplication, QImage, qRgb, qRgba
def skip_if_qt_is_not_installed(_):
pass
else:
def skip_if_qt_is_not_installed(test_case):
test_case.skipTest('PyQt4, PyQt5, or PySide is not installed')
class PillowQtTestCase:
def setUp(self):
try:
@ -27,6 +26,24 @@ class TestImageQt(PillowTestCase):
from PySide.QtGui import QImage, qRgb, qRgba
except ImportError:
self.skipTest('PyQt4 or 5 or PySide not installed')
skip_if_qt_is_not_installed(self)
def tearDown(self):
pass
class PillowQPixmapTestCase(PillowQtTestCase):
def setUp(self):
PillowQtTestCase.setUp(self)
self.app = QGuiApplication([])
def tearDown(self):
PillowQtTestCase.tearDown(self)
self.app.quit()
class TestImageQt(PillowQtTestCase, PillowTestCase):
def test_rgb(self):
# from https://qt-project.org/doc/qt-4.8/qcolor.html
@ -48,10 +65,6 @@ class TestImageQt(PillowTestCase):
checkrgb(0, 255, 0)
checkrgb(0, 0, 255)
def test_image(self):
for mode in ('1', 'RGB', 'RGBA', 'L', 'P'):
ImageQt.ImageQt(hopper(mode))
if __name__ == '__main__':
unittest.main()