Ejemplo n.º 1
0
def toimage(im):
    if hasattr(im, "toUtf8"):
        # FIXME - is this really the best way to do this?
        im = unicode(im.toUtf8(), "utf-8")
    if Image.isStringType(im):
        im = Image.open(im)
    return ImageQt(im)
Ejemplo n.º 2
0
def image_tint(src, tint='#ffffff'):
    if Image.isStringType(src):  # file path?
        src = Image.open(src)
    if src.mode not in ['RGB', 'RGBA']:
        raise TypeError('Unsupported source image mode: {}'.format(src.mode))
    src.load()

    tr, tg, tb = getrgb(tint)
    tl = getcolor(tint, "L")  # tint color's overall luminosity
    if not tl: tl = 1  # avoid division by zero
    tl = float(tl)  # compute luminosity preserving tint factors
    sr, sg, sb = map(lambda tv: tv/tl, (tr, tg, tb))  # per component adjustments

    # create look-up tables to map luminosity to adjusted tint
    # (using floating-point math only to compute table)
    luts = (map(lambda lr: int(lr*sr + 0.5), range(256)) +
            map(lambda lg: int(lg*sg + 0.5), range(256)) +
            map(lambda lb: int(lb*sb + 0.5), range(256)))
    l = grayscale(src)  # 8-bit luminosity version of whole image
    if Image.getmodebands(src.mode) < 4:
        merge_args = (src.mode, (l, l, l))  # for RGB verion of grayscale
    else:  # include copy of src image's alpha layer
        a = Image.new("L", src.size)
        a.putdata(src.getdata(3))
        merge_args = (src.mode, (l, l, l, a))  # for RGBA verion of grayscale
        luts += range(256)  # for 1:1 mapping of copied alpha values

    return Image.merge(*merge_args).point(luts)
Ejemplo n.º 3
0
Archivo: ImageDraw.py Proyecto: nh/imgc
 def setink(self, ink):
     # compatibility
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
Ejemplo n.º 4
0
def grabclipboard():
    debug = 0 # temporary interface
    data = Image.core.grabclipboard(debug)
    if Image.isStringType(data):
        import BmpImagePlugin, StringIO
        return BmpImagePlugin.DibImageFile(StringIO.StringIO(data))
    return data
Ejemplo n.º 5
0
 def tostring(self):
     # experimental: convert palette to string
     if self.rawmode:
         raise ValueError("palette contains raw palette data")
     if Image.isStringType(self.palette):
         return self.palette
     return array.array("B", self.palette).tostring()
Ejemplo n.º 6
0
 def setink(self, ink):
     # compatibility
     if warnings:
         warnings.warn("'setink' is deprecated; use keyword arguments instead", DeprecationWarning, stacklevel=2)
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
Ejemplo n.º 7
0
 def __init__(self, profile):
     # accepts a string (filename), a file-like object, or a low-level
     # profile object
     if Image.isStringType(profile):
         self._set(core.profile_open(profile), profile)
     elif hasattr(profile, "read"):
         self._set(core.profile_fromstring(profile.read()))
     else:
         self._set(profile) # assume it's already a profile
Ejemplo n.º 8
0
 def _getink(self, ink, fill=None):
     if ink is None and fill is None:
         if self.fill:
             fill = self.ink
         else:
             ink = self.ink
     else:
         if ink is not None:
             if Image.isStringType(ink):
                 ink = ImageColor.getcolor(ink, self.mode)
             if self.palette and not Image.isNumberType(ink):
                 ink = self.palette.getcolor(ink)
             ink = self.draw.draw_ink(ink, self.mode)
         if fill is not None:
             if Image.isStringType(fill):
                 fill = ImageColor.getcolor(fill, self.mode)
             if self.palette and not Image.isNumberType(fill):
                 fill = self.palette.getcolor(fill)
             fill = self.draw.draw_ink(fill, self.mode)
     return ink, fill
Ejemplo n.º 9
0
def get_ink_with_alpha(self, fill=None, alpha=None):
	ink = self.ink if (fill == None) else fill
	if ink == None:
		return ink
	if Image.isStringType(ink):
		ink = ImageColor.getcolor(ink, self.mode)
	if self.palette and not Image.isNumberType(ink):
		ink = self.palette.getcolor(ink)
	if alpha != None: #and self.mode == "RGBA"
		ink = ink[:3]+(alpha,)
	#print ink
	return self.draw.draw_ink(ink, self.mode)
Ejemplo n.º 10
0
def get_ink_with_alpha(self, fill=None, alpha=None):
    ink = self.ink if (fill == None) else fill
    if ink == None:
        return ink
    if Image.isStringType(ink):
        ink = ImageColor.getcolor(ink, self.mode)
    if self.palette and not Image.isNumberType(ink):
        ink = self.palette.getcolor(ink)
    if alpha != None:  #and self.mode == "RGBA"
        ink = ink[:3] + (alpha, )
    #print ink
    return self.draw.draw_ink(ink, self.mode)
Ejemplo n.º 11
0
 def setink(self, ink):
     # compatibility
     if warnings:
         warnings.warn(
             "'setink' is deprecated; use keyword arguments instead",
             DeprecationWarning,
             stacklevel=2)
     if Image.isStringType(ink):
         ink = ImageColor.getcolor(ink, self.mode)
     if self.palette and not Image.isNumberType(ink):
         ink = self.palette.getcolor(ink)
     self.ink = self.draw.draw_ink(ink, self.mode)
Ejemplo n.º 12
0
    def __init__(self, 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?
            im = unicode(im.toUtf8(), "utf-8")
        if Image.isStringType(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.tostring("raw", "BGRX")
            format = QImage.Format_RGB32
        elif im.mode == "RGBA":
            try:
                data = im.tostring("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
        else:
            raise ValueError("unsupported image mode %r" % im.mode)

        # must keep a reference, or Qt will crash!
        self.__data = data or im.tostring()

        QImage.__init__(self, self.__data, im.size[0], im.size[1], format)

        if colortable:
            self.setColorTable(colortable)
Ejemplo n.º 13
0
    def __init__(self, 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?
            im = unicode(im.toUtf8(), "utf-8")
        if Image.isStringType(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.tostring("raw", "BGRX")
            format = QImage.Format_RGB32
        elif im.mode == "RGBA":
            try:
                data = im.tostring("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
        else:
            raise ValueError("unsupported image mode %r" % im.mode)

        # must keep a reference, or Qt will crash!
        self.__data = data or im.tostring()

        QImage.__init__(self, self.__data, im.size[0], im.size[1], format)

        if colortable:
            self.setColorTable(colortable)
Ejemplo n.º 14
0
    def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1  # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError as v:  # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except TypeError as v:  # end of data (ord)
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except KeyError as v:  # unsupported mode
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except EOFError as v:  # got header but not the first frame
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)

        if not self.mode or self.size[0] <= 0:
            raise SyntaxError("not identified by this driver")
Ejemplo n.º 15
0
 def getcolor(self, color):
     # experimental: given an rgb tuple, allocate palette entry
     if self.rawmode:
         raise ValueError("palette contains raw palette data")
     if Image.isTupleType(color):
         try:
             return self.colors[color]
         except KeyError:
             # allocate new color slot
             if Image.isStringType(self.palette):
                 self.palette = map(int, self.palette)
             index = len(self.colors)
             if index >= 256:
                 raise ValueError("cannot allocate more than 256 colors")
             self.colors[color] = index
             self.palette[index] = color[0]
             self.palette[index + 256] = color[1]
             self.palette[index + 512] = color[2]
             self.dirty = 1
             return index
     else:
         raise ValueError("unknown color specifier: %r" % color)
Ejemplo n.º 16
0
 def getcolor(self, color):
     # experimental: given an rgb tuple, allocate palette entry
     if self.rawmode:
         raise ValueError("palette contains raw palette data")
     if Image.isTupleType(color):
         try:
             return self.colors[color]
         except KeyError:
             # allocate new color s**t
             if Image.isStringType(self.palette):
                 self.palette = list(self.palette)
             index = len(self.colors)
             if index >= 256:
                 raise ValueError("cannot allocate more than 256 colors")
             self.colors[color] = index
             self.palette[index] = color[0]
             self.palette[index+256] = color[1]
             self.palette[index+512] = color[2]
             self.dirty = 1
             return index
     else:
         raise ValueError("unknown color specifier: %r" % color)
Ejemplo n.º 17
0
    def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1 # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError as v: # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except TypeError as v: # end of data (ord)
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except KeyError as v: # unsupported mode
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)
        except EOFError as v: # got header but not the first frame
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError(v)

        if not self.mode or self.size[0] <= 0:
            raise SyntaxError("not identified by this driver")
Ejemplo n.º 18
0
    def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1  # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError, v:  # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError, v
Ejemplo n.º 19
0
    def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1 # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError, v: # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError, v
Ejemplo n.º 20
0
def _color(color, mode):
    if Image.isStringType(color):
        import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color
Ejemplo n.º 21
0
def _color(color, mode):
    if Image.isStringType(color):
        import ImageColor
        color = ImageColor.getcolor(color, mode)
    return color
Ejemplo n.º 22
0
    def save(self, fp):

        o16 = self.o16
        o32 = self.o32

        fp.write(o16(len(self.tags)))

        # always write in ascending tag order
        tags = list(self.tags.items())
        tags.sort()

        directory = []
        append = directory.append

        offset = fp.tell() + len(self.tags) * 12 + 4

        stripoffsets = None

        # pass 1: convert tags to binary format
        for tag, value in tags:

            typ = None

            if tag in self.tagtype:
                typ = self.tagtype[tag]

            if typ == 1:
                # byte data
                data = value = "".join(map(chr, value))
            elif typ == 7:
                # untyped data
                data = value = "".join(value)
            elif Image.isStringType(value[0]):
                # string data
                typ = 2
                data = value = "\0".join(value) + "\0"
            else:
                # integer data
                if tag == STRIPOFFSETS:
                    stripoffsets = len(directory)
                    typ = 4  # to avoid catch-22
                elif tag in (X_RESOLUTION, Y_RESOLUTION):
                    # identify rational data fields
                    typ = 5
                elif not typ:
                    typ = 3
                    for v in value:
                        if v >= 65536:
                            typ = 4
                if typ == 3:
                    data = "".join(map(o16, value))
                else:
                    data = "".join(map(o32, value))

            if Image.DEBUG:
                import TiffTags
                tagname = TiffTags.TAGS.get(tag, "unknown")
                typname = TiffTags.TYPES.get(typ, "unknown")
                print "save: %s (%d)" % (tagname, tag),
                print "- type: %s (%d)" % (typname, typ),
                if tag in (COLORMAP, IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK,
                           ICCPROFILE, XMP):
                    size = len(data)
                    print "- value: <table: %d bytes>" % size
                else:
                    print "- value:", value

            # figure out if data fits into the directory
            if len(data) == 4:
                append((tag, typ, len(value), data, ""))
            elif len(data) < 4:
                append(
                    (tag, typ, len(value), data + (4 - len(data)) * "\0", ""))
            else:
                count = len(value)
                if typ == 5:
                    count = count // 2  # adjust for rational data field
                append((tag, typ, count, o32(offset), data))
                offset = offset + len(data)
                if offset & 1:
                    offset = offset + 1  # word padding

        # update strip offset data to point beyond auxiliary data
        if stripoffsets is not None:
            tag, typ, count, value, data = directory[stripoffsets]
            assert not data, "multistrip support not yet implemented"
            value = o32(self.i32(value) + offset)
            directory[stripoffsets] = tag, typ, count, value, data

        # pass 2: write directory to file
        for tag, typ, count, value, data in directory:
            if Image.DEBUG > 1:
                print tag, typ, count, repr(value), repr(data)
            fp.write(o16(tag) + o16(typ) + o32(count) + value)

        # -- overwrite here for multi-page --
        fp.write("\0\0\0\0")  # end of directory

        # pass 3: write auxiliary data to file
        for tag, typ, count, value, data in directory:
            fp.write(data)
            if len(data) & 1:
                fp.write("\0")

        return offset
Ejemplo n.º 23
0
    def save(self, fp):

        o16 = self.o16
        o32 = self.o32

        fp.write(o16(len(self.tags)))

        # always write in ascending tag order
        tags = list(self.tags.items())
        tags.sort()

        directory = []
        append = directory.append

        offset = fp.tell() + len(self.tags) * 12 + 4

        stripoffsets = None

        # pass 1: convert tags to binary format
        for tag, value in tags:

            typ = None

            if tag in self.tagtype:
                typ = self.tagtype[tag]

            if typ == 1:
                # byte data
                data = value = "".join(map(chr, value))
            elif typ == 7:
                # untyped data
                data = value = "".join(value)
            elif Image.isStringType(value[0]):
                # string data
                typ = 2
                data = value = "\0".join(value) + "\0"
            else:
                # integer data
                if tag == STRIPOFFSETS:
                    stripoffsets = len(directory)
                    typ = 4 # to avoid catch-22
                elif tag in (X_RESOLUTION, Y_RESOLUTION):
                    # identify rational data fields
                    typ = 5
                elif not typ:
                    typ = 3
                    for v in value:
                        if v >= 65536:
                            typ = 4
                if typ == 3:
                    data = "".join(map(o16, value))
                else:
                    data = "".join(map(o32, value))

            if Image.DEBUG:
                import TiffTags
                tagname = TiffTags.TAGS.get(tag, "unknown")
                typname = TiffTags.TYPES.get(typ, "unknown")
                print "save: %s (%d)" % (tagname, tag),
                print "- type: %s (%d)" % (typname, typ),
                if tag in (COLORMAP, IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, ICCPROFILE, XMP):
                    size = len(data)
                    print "- value: <table: %d bytes>" % size
                else:
                    print "- value:", value

            # figure out if data fits into the directory
            if len(data) == 4:
                append((tag, typ, len(value), data, ""))
            elif len(data) < 4:
                append((tag, typ, len(value), data + (4-len(data))*"\0", ""))
            else:
                count = len(value)
                if typ == 5:
                    count = count // 2        # adjust for rational data field
                append((tag, typ, count, o32(offset), data))
                offset = offset + len(data)
                if offset & 1:
                    offset = offset + 1 # word padding

        # update strip offset data to point beyond auxiliary data
        if stripoffsets is not None:
            tag, typ, count, value, data = directory[stripoffsets]
            assert not data, "multistrip support not yet implemented"
            value = o32(self.i32(value) + offset)
            directory[stripoffsets] = tag, typ, count, value, data

        # pass 2: write directory to file
        for tag, typ, count, value, data in directory:
            if Image.DEBUG > 1:
                print tag, typ, count, repr(value), repr(data)
            fp.write(o16(tag) + o16(typ) + o32(count) + value)

        # -- overwrite here for multi-page --
        fp.write("\0\0\0\0") # end of directory

        # pass 3: write auxiliary data to file
        for tag, typ, count, value, data in directory:
            fp.write(data)
            if len(data) & 1:
                fp.write("\0")

        return offset