We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Import matplotlib qt4 backend after import PIL ImageQt when PyQt5 is installed causes exception
### What did you do?

```python
from PyQt4 import QtCore
from PIL.ImageQt import ImageQt
from matplotlib.backends.backend_qt4agg import (FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
```

### What did you expect to happen?
Import PIL and matplotlib using PyQt4 (in an environment with PyQt5 also installed...)

### What actually happened?
RuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class

Note that this is related, to me, with issue #1939 (closed): https://github.com/python-pillow/Pillow/issues/1939

### What versions of Pillow and Python are you using?
Python 3.4.5
PIL 4.2.1
matplotlib 2.1.0

Please include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive.

The best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as plone, Django, or buildout, try to replicate the issue just using Pillow. 

```
Python 3.4.5 (default, May 29 2017, 15:17:55) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import sys
>>> 
>>> 'PyQt4' in sys.modules
False
>>> 'PyQt5' in sys.modules
False
>>> 
>>> from PyQt4 import QtCore
>>> 'PyQt4' in sys.modules
True
>>> 'PyQt5' in sys.modules
False
>>> 
>>> from PIL.ImageQt import ImageQt
Imported PyQt4... OK!
>>> 
>>> 'PyQt4' in sys.modules
True
>>> 'PyQt5' in sys.modules
True
>>> 
>>> from matplotlib.backends.backend_qt4agg import (FigureCanvasQTAgg as FigureCanvas,
...     NavigationToolbar2QT as NavigationToolbar)
<module 'PyQt5' from '/usr/lib64/python3.4/site-packages/PyQt5/__init__.py'>
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.4/site-packages/matplotlib/backends/backend_qt4agg.py", line 10, in <module>
    from .backend_qt4 import (
  File "/usr/lib64/python3.4/site-packages/matplotlib/backends/backend_qt4.py", line 18, in <module>
    from .qt_compat import QtCore, QtWidgets, _getSaveFileName, __version__
  File "/usr/lib64/python3.4/site-packages/matplotlib/backends/qt_compat.py", line 153, in <module>
    from PyQt5 import QtCore, QtGui, QtWidgets
RuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class
>>> 
```
A try to fix it, is this (currently used in our production environment):

\# /usr/lib64/python3.4/site-packages/PIL/ImageQt.py

```python
(...)
import sys

from . import Image
from ._util import isPath
from io import BytesIO

qt_is_installed = True
qt_version = None
try:
    from PyQt5.QtGui import QImage, qRgba, QPixmap
    from PyQt5.QtCore import QBuffer, QIODevice
    qt_version = '5'
except (ImportError, RuntimeError):
    try:
        del sys.modules['PyQt5']
    except:
        pass

    try:
        from PyQt4.QtGui import QImage, qRgba, QPixmap
        from PyQt4.QtCore import QBuffer, QIODevice
        qt_version = '4'
    except (ImportError, RuntimeError):
        try:
            del sys.modules['PyQt4']
        except:
            pass

        try:
            from PySide.QtGui import QImage, qRgba, QPixmap
            from PySide.QtCore import QBuffer, QIODevice
            qt_version = 'side'
        except ImportError:
            qt_is_installed = False
(...)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/PIL/ImageQt.py`
Content:
```
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 
19 from . import Image
20 from ._util import isPath, py3
21 from io import BytesIO
22 
23 qt_is_installed = True
24 qt_version = None
25 try:
26     from PyQt5.QtGui import QImage, qRgba, QPixmap
27     from PyQt5.QtCore import QBuffer, QIODevice
28     qt_version = '5'
29 except (ImportError, RuntimeError):
30     try:
31         from PyQt4.QtGui import QImage, qRgba, QPixmap
32         from PyQt4.QtCore import QBuffer, QIODevice
33         qt_version = '4'
34     except (ImportError, RuntimeError):
35         try:
36             from PySide.QtGui import QImage, qRgba, QPixmap
37             from PySide.QtCore import QBuffer, QIODevice
38             qt_version = 'side'
39         except ImportError:
40             qt_is_installed = False
41 
42 
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 
49 
50 def fromqimage(im):
51     """
52     :param im: A PIL Image object, or a file name
53     (given either as Python string or a PyQt string object)
54     """
55     buffer = QBuffer()
56     buffer.open(QIODevice.ReadWrite)
57     # preserve alha channel with png
58     # otherwise ppm is more friendly with Image.open
59     if im.hasAlphaChannel():
60         im.save(buffer, 'png')
61     else:
62         im.save(buffer, 'ppm')
63 
64     b = BytesIO()
65     try:
66         b.write(buffer.data())
67     except TypeError:
68         # workaround for Python 2
69         b.write(str(buffer.data()))
70     buffer.close()
71     b.seek(0)
72 
73     return Image.open(b)
74 
75 
76 def fromqpixmap(im):
77     return fromqimage(im)
78     # buffer = QBuffer()
79     # buffer.open(QIODevice.ReadWrite)
80     # # im.save(buffer)
81     # # What if png doesn't support some image features like animation?
82     # im.save(buffer, 'ppm')
83     # bytes_io = BytesIO()
84     # bytes_io.write(buffer.data())
85     # buffer.close()
86     # bytes_io.seek(0)
87     # return Image.open(bytes_io)
88 
89 
90 def align8to32(bytes, width, mode):
91     """
92     converts each scanline of data from 8 bit to 32 bit aligned
93     """
94 
95     bits_per_pixel = {
96         '1': 1,
97         'L': 8,
98         'P': 8,
99     }[mode]
100 
101     # calculate bytes per line and the extra padding if needed
102     bits_per_line = bits_per_pixel * width
103     full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)
104     bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)
105 
106     extra_padding = -bytes_per_line % 4
107 
108     # already 32 bit aligned by luck
109     if not extra_padding:
110         return bytes
111 
112     new_data = []
113     for i in range(len(bytes) // bytes_per_line):
114         new_data.append(bytes[i*bytes_per_line:(i+1)*bytes_per_line] + b'\x00' * extra_padding)
115 
116     return b''.join(new_data)
117 
118 
119 def _toqclass_helper(im):
120     data = None
121     colortable = None
122 
123     # handle filename, if given instead of image name
124     if hasattr(im, "toUtf8"):
125         # FIXME - is this really the best way to do this?
126         if py3:
127             im = str(im.toUtf8(), "utf-8")
128         else:
129             im = unicode(im.toUtf8(), "utf-8")
130     if isPath(im):
131         im = Image.open(im)
132 
133     if im.mode == "1":
134         format = QImage.Format_Mono
135     elif im.mode == "L":
136         format = QImage.Format_Indexed8
137         colortable = []
138         for i in range(256):
139             colortable.append(rgb(i, i, i))
140     elif im.mode == "P":
141         format = QImage.Format_Indexed8
142         colortable = []
143         palette = im.getpalette()
144         for i in range(0, len(palette), 3):
145             colortable.append(rgb(*palette[i:i+3]))
146     elif im.mode == "RGB":
147         data = im.tobytes("raw", "BGRX")
148         format = QImage.Format_RGB32
149     elif im.mode == "RGBA":
150         try:
151             data = im.tobytes("raw", "BGRA")
152         except SystemError:
153             # workaround for earlier versions
154             r, g, b, a = im.split()
155             im = Image.merge("RGBA", (b, g, r, a))
156         format = QImage.Format_ARGB32
157     else:
158         raise ValueError("unsupported image mode %r" % im.mode)
159 
160     __data = data or align8to32(im.tobytes(), im.size[0], im.mode)
161     return {
162         'data': __data, 'im': im, 'format': format, 'colortable': colortable
163     }
164 
165 
166 if qt_is_installed:
167     class ImageQt(QImage):
168 
169         def __init__(self, im):
170             """
171             An PIL image wrapper for Qt.  This is a subclass of PyQt's QImage
172             class.
173 
174             :param im: A PIL Image object, or a file name (given either as Python
175                 string or a PyQt string object).
176             """
177             im_data = _toqclass_helper(im)
178             # must keep a reference, or Qt will crash!
179             # All QImage constructors that take data operate on an existing
180             # buffer, so this buffer has to hang on for the life of the image.
181             # Fixes https://github.com/python-pillow/Pillow/issues/1370
182             self.__data = im_data['data']
183             QImage.__init__(self,
184                             self.__data, im_data['im'].size[0],
185                             im_data['im'].size[1], im_data['format'])
186             if im_data['colortable']:
187                 self.setColorTable(im_data['colortable'])
188 
189 
190 def toqimage(im):
191     return ImageQt(im)
192 
193 
194 def toqpixmap(im):
195     # # This doesn't work. For now using a dumb approach.
196     # im_data = _toqclass_helper(im)
197     # result = QPixmap(im_data['im'].size[0], im_data['im'].size[1])
198     # result.loadFromData(im_data['data'])
199     # Fix some strange bug that causes
200     if im.mode == 'RGB':
201         im = im.convert('RGBA')
202 
203     qimage = toqimage(im)
204     return QPixmap.fromImage(qimage)
205
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/PIL/ImageQt.py b/src/PIL/ImageQt.py
--- a/src/PIL/ImageQt.py
+++ b/src/PIL/ImageQt.py
@@ -19,25 +19,33 @@
 from . import Image
 from ._util import isPath, py3
 from io import BytesIO
-
-qt_is_installed = True
-qt_version = None
-try:
-    from PyQt5.QtGui import QImage, qRgba, QPixmap
-    from PyQt5.QtCore import QBuffer, QIODevice
-    qt_version = '5'
-except (ImportError, RuntimeError):
+import sys
+
+qt_versions = [
+    ['5', 'PyQt5'],
+    ['4', 'PyQt4'],
+    ['side', 'PySide']
+]
+# If a version has already been imported, attempt it first
+qt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True)
+for qt_version, qt_module in qt_versions:
     try:
-        from PyQt4.QtGui import QImage, qRgba, QPixmap
-        from PyQt4.QtCore import QBuffer, QIODevice
-        qt_version = '4'
-    except (ImportError, RuntimeError):
-        try:
+        if qt_module == 'PyQt5':
+            from PyQt5.QtGui import QImage, qRgba, QPixmap
+            from PyQt5.QtCore import QBuffer, QIODevice
+        elif qt_module == 'PyQt4':
+            from PyQt4.QtGui import QImage, qRgba, QPixmap
+            from PyQt4.QtCore import QBuffer, QIODevice
+        elif qt_module == 'PySide':
             from PySide.QtGui import QImage, qRgba, QPixmap
             from PySide.QtCore import QBuffer, QIODevice
-            qt_version = 'side'
-        except ImportError:
-            qt_is_installed = False
+    except (ImportError, RuntimeError):
+        continue
+    qt_is_installed = True
+    break
+else:
+    qt_is_installed = False
+    qt_version = None
 
 
 def rgb(r, g, b, a=255):

{"golden_diff": "diff --git a/src/PIL/ImageQt.py b/src/PIL/ImageQt.py\n--- a/src/PIL/ImageQt.py\n+++ b/src/PIL/ImageQt.py\n@@ -19,25 +19,33 @@\n from . import Image\n from ._util import isPath, py3\n from io import BytesIO\n-\n-qt_is_installed = True\n-qt_version = None\n-try:\n-    from PyQt5.QtGui import QImage, qRgba, QPixmap\n-    from PyQt5.QtCore import QBuffer, QIODevice\n-    qt_version = '5'\n-except (ImportError, RuntimeError):\n+import sys\n+\n+qt_versions = [\n+    ['5', 'PyQt5'],\n+    ['4', 'PyQt4'],\n+    ['side', 'PySide']\n+]\n+# If a version has already been imported, attempt it first\n+qt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True)\n+for qt_version, qt_module in qt_versions:\n     try:\n-        from PyQt4.QtGui import QImage, qRgba, QPixmap\n-        from PyQt4.QtCore import QBuffer, QIODevice\n-        qt_version = '4'\n-    except (ImportError, RuntimeError):\n-        try:\n+        if qt_module == 'PyQt5':\n+            from PyQt5.QtGui import QImage, qRgba, QPixmap\n+            from PyQt5.QtCore import QBuffer, QIODevice\n+        elif qt_module == 'PyQt4':\n+            from PyQt4.QtGui import QImage, qRgba, QPixmap\n+            from PyQt4.QtCore import QBuffer, QIODevice\n+        elif qt_module == 'PySide':\n             from PySide.QtGui import QImage, qRgba, QPixmap\n             from PySide.QtCore import QBuffer, QIODevice\n-            qt_version = 'side'\n-        except ImportError:\n-            qt_is_installed = False\n+    except (ImportError, RuntimeError):\n+        continue\n+    qt_is_installed = True\n+    break\n+else:\n+    qt_is_installed = False\n+    qt_version = None\n \n \n def rgb(r, g, b, a=255):\n", "issue": "Import matplotlib qt4 backend after import PIL ImageQt when PyQt5 is installed causes exception\n### What did you do?\r\n\r\n```python\r\nfrom PyQt4 import QtCore\r\nfrom PIL.ImageQt import ImageQt\r\nfrom matplotlib.backends.backend_qt4agg import (FigureCanvasQTAgg as FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\r\n```\r\n\r\n### What did you expect to happen?\r\nImport PIL and matplotlib using PyQt4 (in an environment with PyQt5 also installed...)\r\n\r\n### What actually happened?\r\nRuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class\r\n\r\nNote that this is related, to me, with issue #1939 (closed): https://github.com/python-pillow/Pillow/issues/1939\r\n\r\n### What versions of Pillow and Python are you using?\r\nPython 3.4.5\r\nPIL 4.2.1\r\nmatplotlib 2.1.0\r\n\r\nPlease include **code** that reproduces the issue and whenever possible, an **image** that demonstrates the issue. Please upload images to GitHub, not to third-party file hosting sites. If necessary, add the image to a zip or tar archive.\r\n\r\nThe best reproductions are self-contained scripts with minimal dependencies. If you are using a framework such as plone, Django, or buildout, try to replicate the issue just using Pillow. \r\n\r\n```\r\nPython 3.4.5 (default, May 29 2017, 15:17:55) \r\n[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> \r\n>>> import sys\r\n>>> \r\n>>> 'PyQt4' in sys.modules\r\nFalse\r\n>>> 'PyQt5' in sys.modules\r\nFalse\r\n>>> \r\n>>> from PyQt4 import QtCore\r\n>>> 'PyQt4' in sys.modules\r\nTrue\r\n>>> 'PyQt5' in sys.modules\r\nFalse\r\n>>> \r\n>>> from PIL.ImageQt import ImageQt\r\nImported PyQt4... OK!\r\n>>> \r\n>>> 'PyQt4' in sys.modules\r\nTrue\r\n>>> 'PyQt5' in sys.modules\r\nTrue\r\n>>> \r\n>>> from matplotlib.backends.backend_qt4agg import (FigureCanvasQTAgg as FigureCanvas,\r\n...     NavigationToolbar2QT as NavigationToolbar)\r\n<module 'PyQt5' from '/usr/lib64/python3.4/site-packages/PyQt5/__init__.py'>\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\n  File \"/usr/lib64/python3.4/site-packages/matplotlib/backends/backend_qt4agg.py\", line 10, in <module>\r\n    from .backend_qt4 import (\r\n  File \"/usr/lib64/python3.4/site-packages/matplotlib/backends/backend_qt4.py\", line 18, in <module>\r\n    from .qt_compat import QtCore, QtWidgets, _getSaveFileName, __version__\r\n  File \"/usr/lib64/python3.4/site-packages/matplotlib/backends/qt_compat.py\", line 153, in <module>\r\n    from PyQt5 import QtCore, QtGui, QtWidgets\r\nRuntimeError: the PyQt5.QtCore and PyQt4.QtCore modules both wrap the QObject class\r\n>>> \r\n```\r\nA try to fix it, is this (currently used in our production environment):\r\n\r\n\\# /usr/lib64/python3.4/site-packages/PIL/ImageQt.py\r\n\r\n```python\r\n(...)\r\nimport sys\r\n\r\nfrom . import Image\r\nfrom ._util import isPath\r\nfrom io import BytesIO\r\n\r\nqt_is_installed = True\r\nqt_version = None\r\ntry:\r\n    from PyQt5.QtGui import QImage, qRgba, QPixmap\r\n    from PyQt5.QtCore import QBuffer, QIODevice\r\n    qt_version = '5'\r\nexcept (ImportError, RuntimeError):\r\n    try:\r\n        del sys.modules['PyQt5']\r\n    except:\r\n        pass\r\n\r\n    try:\r\n        from PyQt4.QtGui import QImage, qRgba, QPixmap\r\n        from PyQt4.QtCore import QBuffer, QIODevice\r\n        qt_version = '4'\r\n    except (ImportError, RuntimeError):\r\n        try:\r\n            del sys.modules['PyQt4']\r\n        except:\r\n            pass\r\n\r\n        try:\r\n            from PySide.QtGui import QImage, qRgba, QPixmap\r\n            from PySide.QtCore import QBuffer, QIODevice\r\n            qt_version = 'side'\r\n        except ImportError:\r\n            qt_is_installed = False\r\n(...)\r\n```\n", "before_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# a simple Qt image interface.\n#\n# history:\n# 2006-06-03 fl: created\n# 2006-06-04 fl: inherit from QImage instead of wrapping it\n# 2006-06-05 fl: removed toimage helper; move string support to ImageQt\n# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)\n#\n# Copyright (c) 2006 by Secret Labs AB\n# Copyright (c) 2006 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom . import Image\nfrom ._util import isPath, py3\nfrom io import BytesIO\n\nqt_is_installed = True\nqt_version = None\ntry:\n    from PyQt5.QtGui import QImage, qRgba, QPixmap\n    from PyQt5.QtCore import QBuffer, QIODevice\n    qt_version = '5'\nexcept (ImportError, RuntimeError):\n    try:\n        from PyQt4.QtGui import QImage, qRgba, QPixmap\n        from PyQt4.QtCore import QBuffer, QIODevice\n        qt_version = '4'\n    except (ImportError, RuntimeError):\n        try:\n            from PySide.QtGui import QImage, qRgba, QPixmap\n            from PySide.QtCore import QBuffer, QIODevice\n            qt_version = 'side'\n        except ImportError:\n            qt_is_installed = False\n\n\ndef rgb(r, g, b, a=255):\n    \"\"\"(Internal) Turns an RGB color into a Qt compatible color integer.\"\"\"\n    # use qRgb to pack the colors, and then turn the resulting long\n    # into a negative integer with the same bitpattern.\n    return (qRgba(r, g, b, a) & 0xffffffff)\n\n\ndef fromqimage(im):\n    \"\"\"\n    :param im: A PIL Image object, or a file name\n    (given either as Python string or a PyQt string object)\n    \"\"\"\n    buffer = QBuffer()\n    buffer.open(QIODevice.ReadWrite)\n    # preserve alha channel with png\n    # otherwise ppm is more friendly with Image.open\n    if im.hasAlphaChannel():\n        im.save(buffer, 'png')\n    else:\n        im.save(buffer, 'ppm')\n\n    b = BytesIO()\n    try:\n        b.write(buffer.data())\n    except TypeError:\n        # workaround for Python 2\n        b.write(str(buffer.data()))\n    buffer.close()\n    b.seek(0)\n\n    return Image.open(b)\n\n\ndef fromqpixmap(im):\n    return fromqimage(im)\n    # buffer = QBuffer()\n    # buffer.open(QIODevice.ReadWrite)\n    # # im.save(buffer)\n    # # What if png doesn't support some image features like animation?\n    # im.save(buffer, 'ppm')\n    # bytes_io = BytesIO()\n    # bytes_io.write(buffer.data())\n    # buffer.close()\n    # bytes_io.seek(0)\n    # return Image.open(bytes_io)\n\n\ndef align8to32(bytes, width, mode):\n    \"\"\"\n    converts each scanline of data from 8 bit to 32 bit aligned\n    \"\"\"\n\n    bits_per_pixel = {\n        '1': 1,\n        'L': 8,\n        'P': 8,\n    }[mode]\n\n    # calculate bytes per line and the extra padding if needed\n    bits_per_line = bits_per_pixel * width\n    full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)\n    bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)\n\n    extra_padding = -bytes_per_line % 4\n\n    # already 32 bit aligned by luck\n    if not extra_padding:\n        return bytes\n\n    new_data = []\n    for i in range(len(bytes) // bytes_per_line):\n        new_data.append(bytes[i*bytes_per_line:(i+1)*bytes_per_line] + b'\\x00' * extra_padding)\n\n    return b''.join(new_data)\n\n\ndef _toqclass_helper(im):\n    data = None\n    colortable = None\n\n    # handle filename, if given instead of image name\n    if hasattr(im, \"toUtf8\"):\n        # FIXME - is this really the best way to do this?\n        if py3:\n            im = str(im.toUtf8(), \"utf-8\")\n        else:\n            im = unicode(im.toUtf8(), \"utf-8\")\n    if isPath(im):\n        im = Image.open(im)\n\n    if im.mode == \"1\":\n        format = QImage.Format_Mono\n    elif im.mode == \"L\":\n        format = QImage.Format_Indexed8\n        colortable = []\n        for i in range(256):\n            colortable.append(rgb(i, i, i))\n    elif im.mode == \"P\":\n        format = QImage.Format_Indexed8\n        colortable = []\n        palette = im.getpalette()\n        for i in range(0, len(palette), 3):\n            colortable.append(rgb(*palette[i:i+3]))\n    elif im.mode == \"RGB\":\n        data = im.tobytes(\"raw\", \"BGRX\")\n        format = QImage.Format_RGB32\n    elif im.mode == \"RGBA\":\n        try:\n            data = im.tobytes(\"raw\", \"BGRA\")\n        except SystemError:\n            # workaround for earlier versions\n            r, g, b, a = im.split()\n            im = Image.merge(\"RGBA\", (b, g, r, a))\n        format = QImage.Format_ARGB32\n    else:\n        raise ValueError(\"unsupported image mode %r\" % im.mode)\n\n    __data = data or align8to32(im.tobytes(), im.size[0], im.mode)\n    return {\n        'data': __data, 'im': im, 'format': format, 'colortable': colortable\n    }\n\n\nif qt_is_installed:\n    class ImageQt(QImage):\n\n        def __init__(self, im):\n            \"\"\"\n            An PIL image wrapper for Qt.  This is a subclass of PyQt's QImage\n            class.\n\n            :param im: A PIL Image object, or a file name (given either as Python\n                string or a PyQt string object).\n            \"\"\"\n            im_data = _toqclass_helper(im)\n            # must keep a reference, or Qt will crash!\n            # All QImage constructors that take data operate on an existing\n            # buffer, so this buffer has to hang on for the life of the image.\n            # Fixes https://github.com/python-pillow/Pillow/issues/1370\n            self.__data = im_data['data']\n            QImage.__init__(self,\n                            self.__data, im_data['im'].size[0],\n                            im_data['im'].size[1], im_data['format'])\n            if im_data['colortable']:\n                self.setColorTable(im_data['colortable'])\n\n\ndef toqimage(im):\n    return ImageQt(im)\n\n\ndef toqpixmap(im):\n    # # This doesn't work. For now using a dumb approach.\n    # im_data = _toqclass_helper(im)\n    # result = QPixmap(im_data['im'].size[0], im_data['im'].size[1])\n    # result.loadFromData(im_data['data'])\n    # Fix some strange bug that causes\n    if im.mode == 'RGB':\n        im = im.convert('RGBA')\n\n    qimage = toqimage(im)\n    return QPixmap.fromImage(qimage)\n", "path": "src/PIL/ImageQt.py"}], "after_files": [{"content": "#\n# The Python Imaging Library.\n# $Id$\n#\n# a simple Qt image interface.\n#\n# history:\n# 2006-06-03 fl: created\n# 2006-06-04 fl: inherit from QImage instead of wrapping it\n# 2006-06-05 fl: removed toimage helper; move string support to ImageQt\n# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)\n#\n# Copyright (c) 2006 by Secret Labs AB\n# Copyright (c) 2006 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom . import Image\nfrom ._util import isPath, py3\nfrom io import BytesIO\nimport sys\n\nqt_versions = [\n    ['5', 'PyQt5'],\n    ['4', 'PyQt4'],\n    ['side', 'PySide']\n]\n# If a version has already been imported, attempt it first\nqt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True)\nfor qt_version, qt_module in qt_versions:\n    try:\n        if qt_module == 'PyQt5':\n            from PyQt5.QtGui import QImage, qRgba, QPixmap\n            from PyQt5.QtCore import QBuffer, QIODevice\n        elif qt_module == 'PyQt4':\n            from PyQt4.QtGui import QImage, qRgba, QPixmap\n            from PyQt4.QtCore import QBuffer, QIODevice\n        elif qt_module == 'PySide':\n            from PySide.QtGui import QImage, qRgba, QPixmap\n            from PySide.QtCore import QBuffer, QIODevice\n    except (ImportError, RuntimeError):\n        continue\n    qt_is_installed = True\n    break\nelse:\n    qt_is_installed = False\n    qt_version = None\n\n\ndef rgb(r, g, b, a=255):\n    \"\"\"(Internal) Turns an RGB color into a Qt compatible color integer.\"\"\"\n    # use qRgb to pack the colors, and then turn the resulting long\n    # into a negative integer with the same bitpattern.\n    return (qRgba(r, g, b, a) & 0xffffffff)\n\n\ndef fromqimage(im):\n    \"\"\"\n    :param im: A PIL Image object, or a file name\n    (given either as Python string or a PyQt string object)\n    \"\"\"\n    buffer = QBuffer()\n    buffer.open(QIODevice.ReadWrite)\n    # preserve alha channel with png\n    # otherwise ppm is more friendly with Image.open\n    if im.hasAlphaChannel():\n        im.save(buffer, 'png')\n    else:\n        im.save(buffer, 'ppm')\n\n    b = BytesIO()\n    try:\n        b.write(buffer.data())\n    except TypeError:\n        # workaround for Python 2\n        b.write(str(buffer.data()))\n    buffer.close()\n    b.seek(0)\n\n    return Image.open(b)\n\n\ndef fromqpixmap(im):\n    return fromqimage(im)\n    # buffer = QBuffer()\n    # buffer.open(QIODevice.ReadWrite)\n    # # im.save(buffer)\n    # # What if png doesn't support some image features like animation?\n    # im.save(buffer, 'ppm')\n    # bytes_io = BytesIO()\n    # bytes_io.write(buffer.data())\n    # buffer.close()\n    # bytes_io.seek(0)\n    # return Image.open(bytes_io)\n\n\ndef align8to32(bytes, width, mode):\n    \"\"\"\n    converts each scanline of data from 8 bit to 32 bit aligned\n    \"\"\"\n\n    bits_per_pixel = {\n        '1': 1,\n        'L': 8,\n        'P': 8,\n    }[mode]\n\n    # calculate bytes per line and the extra padding if needed\n    bits_per_line = bits_per_pixel * width\n    full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)\n    bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)\n\n    extra_padding = -bytes_per_line % 4\n\n    # already 32 bit aligned by luck\n    if not extra_padding:\n        return bytes\n\n    new_data = []\n    for i in range(len(bytes) // bytes_per_line):\n        new_data.append(bytes[i*bytes_per_line:(i+1)*bytes_per_line] + b'\\x00' * extra_padding)\n\n    return b''.join(new_data)\n\n\ndef _toqclass_helper(im):\n    data = None\n    colortable = None\n\n    # handle filename, if given instead of image name\n    if hasattr(im, \"toUtf8\"):\n        # FIXME - is this really the best way to do this?\n        if py3:\n            im = str(im.toUtf8(), \"utf-8\")\n        else:\n            im = unicode(im.toUtf8(), \"utf-8\")\n    if isPath(im):\n        im = Image.open(im)\n\n    if im.mode == \"1\":\n        format = QImage.Format_Mono\n    elif im.mode == \"L\":\n        format = QImage.Format_Indexed8\n        colortable = []\n        for i in range(256):\n            colortable.append(rgb(i, i, i))\n    elif im.mode == \"P\":\n        format = QImage.Format_Indexed8\n        colortable = []\n        palette = im.getpalette()\n        for i in range(0, len(palette), 3):\n            colortable.append(rgb(*palette[i:i+3]))\n    elif im.mode == \"RGB\":\n        data = im.tobytes(\"raw\", \"BGRX\")\n        format = QImage.Format_RGB32\n    elif im.mode == \"RGBA\":\n        try:\n            data = im.tobytes(\"raw\", \"BGRA\")\n        except SystemError:\n            # workaround for earlier versions\n            r, g, b, a = im.split()\n            im = Image.merge(\"RGBA\", (b, g, r, a))\n        format = QImage.Format_ARGB32\n    else:\n        raise ValueError(\"unsupported image mode %r\" % im.mode)\n\n    __data = data or align8to32(im.tobytes(), im.size[0], im.mode)\n    return {\n        'data': __data, 'im': im, 'format': format, 'colortable': colortable\n    }\n\n\nif qt_is_installed:\n    class ImageQt(QImage):\n\n        def __init__(self, im):\n            \"\"\"\n            An PIL image wrapper for Qt.  This is a subclass of PyQt's QImage\n            class.\n\n            :param im: A PIL Image object, or a file name (given either as Python\n                string or a PyQt string object).\n            \"\"\"\n            im_data = _toqclass_helper(im)\n            # must keep a reference, or Qt will crash!\n            # All QImage constructors that take data operate on an existing\n            # buffer, so this buffer has to hang on for the life of the image.\n            # Fixes https://github.com/python-pillow/Pillow/issues/1370\n            self.__data = im_data['data']\n            QImage.__init__(self,\n                            self.__data, im_data['im'].size[0],\n                            im_data['im'].size[1], im_data['format'])\n            if im_data['colortable']:\n                self.setColorTable(im_data['colortable'])\n\n\ndef toqimage(im):\n    return ImageQt(im)\n\n\ndef toqpixmap(im):\n    # # This doesn't work. For now using a dumb approach.\n    # im_data = _toqclass_helper(im)\n    # result = QPixmap(im_data['im'].size[0], im_data['im'].size[1])\n    # result.loadFromData(im_data['data'])\n    # Fix some strange bug that causes\n    if im.mode == 'RGB':\n        im = im.convert('RGBA')\n\n    qimage = toqimage(im)\n    return QPixmap.fromImage(qimage)\n", "path": "src/PIL/ImageQt.py"}]}