~asdfghjkl-deactivatedaccount1/python-imaging/gif-fix

14 by effbot
Load Imaging-1.1.6b1 into pil.
1
#
2
# The Python Imaging Library.
3
# $Id: ImageQt.py 2741 2006-06-18 16:17:20Z fredrik $
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
#
12
# Copyright (c) 2006 by Secret Labs AB
13
# Copyright (c) 2006 by Fredrik Lundh
14
#
15
# See the README file for information on usage and redistribution.
16
#
17
18
import Image
19
20
from PyQt4.QtGui import QImage, qRgb
21
22
##
23
# (Internal) Turns an RGB color into a Qt compatible color integer.
24
25
def rgb(r, g, b):
26
    # use qRgb to pack the colors, and then turn the resulting long
27
    # into a negative integer with the same bitpattern.
28
    return (qRgb(r, g, b) & 0xffffff) - 0x1000000
29
30
##
31
# An PIL image wrapper for Qt.  This is a subclass of PyQt4's QImage
32
# class.
33
#
34
# @param im A PIL Image object, or a file name (given either as Python
35
#     string or a PyQt string object).
36
37
class ImageQt(QImage):
38
39
    def __init__(self, im):
40
41
        data = None
42
        colortable = None
43
44
        # handle filename, if given instead of image name
45
        if hasattr(im, "toUtf8"):
46
            # FIXME - is this really the best way to do this?
47
            im = unicode(im.toUtf8(), "utf-8")
48
        if Image.isStringType(im):
49
            im = Image.open(im)
50
51
        if im.mode == "1":
52
            format = QImage.Format_Mono
53
        elif im.mode == "L":
54
            format = QImage.Format_Indexed8
55
            colortable = []
56
            for i in range(256):
57
                colortable.append(rgb(i, i, i))
58
        elif im.mode == "P":
59
            format = QImage.Format_Indexed8
60
            colortable = []
61
            palette = im.getpalette()
62
            for i in range(0, len(palette), 3):
63
                colortable.append(rgb(*palette[i:i+3]))
64
        elif im.mode == "RGB":
65
            data = im.tostring("raw", "BGRX")
66
            format = QImage.Format_RGB32
67
        elif im.mode == "RGBA":
68
            try:
69
                data = im.tostring("raw", "BGRA")
70
            except SystemError:
71
                # workaround for earlier versions
72
                r, g, b, a = im.split()
73
                im = Image.merge("RGBA", (b, g, r, a))
74
            format = QImage.Format_ARGB32
75
        else:
76
            raise ValueError("unsupported image mode %r" % im.mode)
77
78
        # must keep a reference, or Qt will crash!
79
        self.__data = data or im.tostring()
80
81
        QImage.__init__(self, self.__data, im.size[0], im.size[1], format)
82
83
        if colortable:
84
            self.setColorTable(colortable)