Upload original 计算机组成原理课程实践 学分×2 陈媛媛 course files (part 50)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Proteus 8 Professional/Tools/Python/Lib/PIL/BdfFontFile.py+133-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/BlpImagePlugin.py+435-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/BmpImagePlugin.py+289-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/BufrStubImagePlugin.py+72-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ContainerIO.py+116-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/CurImagePlugin.py+86-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/DcxImagePlugin.py+87-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/DdsImagePlugin.py+172-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/EpsImagePlugin.py+429-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ExifTags.py+315-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/FitsStubImagePlugin.py+75-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/FliImagePlugin.py+163-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/FontFile.py+114-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/FpxImagePlugin.py+229-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/FtexImagePlugin.py+94-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GbrImagePlugin.py+94-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GdImageFile.py+83-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GifImagePlugin.py+814-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GimpGradientFile.py+138-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GimpPaletteFile.py+62-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/GribStubImagePlugin.py+73-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/Hdf5StubImagePlugin.py+72-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/IcnsImagePlugin.py+374-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/IcoImagePlugin.py+284-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImImagePlugin.py+347-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/Image.py+2930-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageChops.py+283-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageCms.py+955-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageColor.py+309-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageDraw.py+387-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageDraw2.py+108-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageEnhance.py+100-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFile.py+667-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFilter.py+486-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFont.py+471-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageGrab.py+80-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMath.py+271-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMode.py+55-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMorph.py+250-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageOps.py+529-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImagePalette.py+216-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImagePath.py+20-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageQt.py+212-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageSequence.py+56-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageShow.py+194-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageStat.py+148-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageTk.py+303-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageTransform.py+98-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImageWin.py+228-3
- Proteus 8 Professional/Tools/Python/Lib/PIL/ImtImagePlugin.py+95-3
123version https://git-lfs.github.com/spec/v1oid sha256:771fbe2731d4c4b8947f47b25b6ce740fe0745ef78d6265f0c89cafe5e80e09dsize 3367123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133## The Python Imaging Library# $Id$## bitmap distribution font (bdf) file parser## history:# 1996-05-16 fl created (as bdf2pil)# 1997-08-25 fl converted to FontFile driver# 2001-05-25 fl removed bogus __init__ call# 2002-11-20 fl robustification (from Kevin Cazabon, Dmitry Vasiliev)# 2003-04-22 fl more robustification (from Graham Dumpleton)## Copyright (c) 1997-2003 by Secret Labs AB.# Copyright (c) 1997-2003 by Fredrik Lundh.## See the README file for information on usage and redistribution.#from __future__ import print_functionfrom . import Image, FontFile# --------------------------------------------------------------------# parse X Bitmap Distribution Format (BDF)# --------------------------------------------------------------------bdf_slant = {"R": "Roman","I": "Italic","O": "Oblique","RI": "Reverse Italic","RO": "Reverse Oblique","OT": "Other"}bdf_spacing = {"P": "Proportional","M": "Monospaced","C": "Cell"}def bdf_char(f):# skip to STARTCHARwhile True:s = f.readline()if not s:return Noneif s[:9] == b"STARTCHAR":breakid = s[9:].strip().decode('ascii')# load symbol propertiesprops = {}while True:s = f.readline()if not s or s[:6] == b"BITMAP":breaki = s.find(b" ")props[s[:i].decode('ascii')] = s[i+1:-1].decode('ascii')# load bitmapbitmap = []while True:s = f.readline()if not s or s[:7] == b"ENDCHAR":breakbitmap.append(s[:-1])bitmap = b"".join(bitmap)[x, y, l, d] = [int(p) for p in props["BBX"].split()][dx, dy] = [int(p) for p in props["DWIDTH"].split()]bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y)try:im = Image.frombytes("1", (x, y), bitmap, "hex", "1")except ValueError:# deal with zero-width charactersim = Image.new("1", (x, y))return id, int(props["ENCODING"]), bbox, im### Font file plugin for the X11 BDF format.class BdfFontFile(FontFile.FontFile):def __init__(self, fp):FontFile.FontFile.__init__(self)s = fp.readline()if s[:13] != b"STARTFONT 2.1":raise SyntaxError("not a valid BDF file")props = {}comments = []while True:s = fp.readline()if not s or s[:13] == b"ENDPROPERTIES":breaki = s.find(b" ")props[s[:i].decode('ascii')] = s[i+1:-1].decode('ascii')if s[:i] in [b"COMMENT", b"COPYRIGHT"]:if s.find(b"LogicalFontDescription") < 0:comments.append(s[i+1:-1].decode('ascii'))# font = props["FONT"].split("-")# font[4] = bdf_slant[font[4].upper()]# font[11] = bdf_spacing[font[11].upper()]# ascent = int(props["FONT_ASCENT"])# descent = int(props["FONT_DESCENT"])# fontname = ";".join(font[1:])# print("#", fontname)# for i in comments:# print("#", i)while True:c = bdf_char(fp)if not c:breakid, ch, (xy, dst, src), im = cif 0 <= ch < len(self.glyph):self.glyph[ch] = xy, dst, src, im
123version https://git-lfs.github.com/spec/v1oid sha256:e34872455832e1b4f291b3bc9ff3fe4ff7be668b097ae1963eccfc4cac13a390size 14415123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435"""Blizzard Mipmap Format (.blp)Jerome Leclanche <jerome@leclan.ch>The contents of this file are hereby released in the public domain (CC0)Full text of the CC0 license:https://creativecommons.org/publicdomain/zero/1.0/BLP1 files, used mostly in Warcraft III, are not fully supported.All types of BLP2 files used in World of Warcraft are supported.The BLP file structure consists of a header, up to 16 mipmaps of thetextureTexture sizes must be powers of two, though the two dimensions donot have to be equal; 512x256 is valid, but 512x200 is not.The first mipmap (mipmap #0) is the full size image; each subsequentmipmap halves both dimensions. The final mipmap should be 1x1.BLP files come in many different flavours:* JPEG-compressed (type == 0) - only supported for BLP1.* RAW images (type == 1, encoding == 1). Each mipmap is stored as anarray of 8-bit values, one per pixel, left to right, top to bottom.Each value is an index to the palette.* DXT-compressed (type == 1, encoding == 2):- DXT1 compression is used if alpha_encoding == 0.- An additional alpha bit is used if alpha_depth == 1.- DXT3 compression is used if alpha_encoding == 1.- DXT5 compression is used if alpha_encoding == 7."""import structfrom io import BytesIOfrom . import Image, ImageFileBLP_FORMAT_JPEG = 0BLP_ENCODING_UNCOMPRESSED = 1BLP_ENCODING_DXT = 2BLP_ENCODING_UNCOMPRESSED_RAW_BGRA = 3BLP_ALPHA_ENCODING_DXT1 = 0BLP_ALPHA_ENCODING_DXT3 = 1BLP_ALPHA_ENCODING_DXT5 = 7def unpack_565(i):return (((i >> 11) & 0x1f) << 3,((i >> 5) & 0x3f) << 2,(i & 0x1f) << 3)def decode_dxt1(data, alpha=False):"""input: one "row" of data (i.e. will produce 4*width pixels)"""blocks = len(data) // 8 # number of blocks in rowret = (bytearray(), bytearray(), bytearray(), bytearray())for block in range(blocks):# Decode next 8-byte block.idx = block * 8color0, color1, bits = struct.unpack_from("<HHI", data, idx)r0, g0, b0 = unpack_565(color0)r1, g1, b1 = unpack_565(color1)# Decode this block into 4x4 pixels# Accumulate the results onto our 4 row accumulatorsfor j in range(4):for i in range(4):# get next control op and generate a pixelcontrol = bits & 3bits = bits >> 2a = 0xFFif control == 0:r, g, b = r0, g0, b0elif control == 1:r, g, b = r1, g1, b1elif control == 2:if color0 > color1:r = (2 * r0 + r1) // 3g = (2 * g0 + g1) // 3b = (2 * b0 + b1) // 3else:r = (r0 + r1) // 2g = (g0 + g1) // 2b = (b0 + b1) // 2elif control == 3:if color0 > color1:r = (2 * r1 + r0) // 3g = (2 * g1 + g0) // 3b = (2 * b1 + b0) // 3else:r, g, b, a = 0, 0, 0, 0if alpha:ret[j].extend([r, g, b, a])else:ret[j].extend([r, g, b])return retdef decode_dxt3(data):"""input: one "row" of data (i.e. will produce 4*width pixels)"""blocks = len(data) // 16 # number of blocks in rowret = (bytearray(), bytearray(), bytearray(), bytearray())for block in range(blocks):idx = block * 16block = data[idx:idx + 16]# Decode next 16-byte block.bits = struct.unpack_from("<8B", block)color0, color1 = struct.unpack_from("<HH", block, 8)code, = struct.unpack_from("<I", block, 12)r0, g0, b0 = unpack_565(color0)r1, g1, b1 = unpack_565(color1)for j in range(4):high = False # Do we want the higher bits?for i in range(4):alphacode_index = (4 * j + i) // 2a = bits[alphacode_index]if high:high = Falsea >>= 4else:high = Truea &= 0xfa *= 17 # We get a value between 0 and 15color_code = (code >> 2 * (4 * j + i)) & 0x03if color_code == 0:r, g, b = r0, g0, b0elif color_code == 1:r, g, b = r1, g1, b1elif color_code == 2:r = (2 * r0 + r1) // 3g = (2 * g0 + g1) // 3b = (2 * b0 + b1) // 3elif color_code == 3:r = (2 * r1 + r0) // 3g = (2 * g1 + g0) // 3b = (2 * b1 + b0) // 3ret[j].extend([r, g, b, a])return retdef decode_dxt5(data):"""input: one "row" of data (i.e. will produce 4 * width pixels)"""blocks = len(data) // 16 # number of blocks in rowret = (bytearray(), bytearray(), bytearray(), bytearray())for block in range(blocks):idx = block * 16block = data[idx:idx + 16]# Decode next 16-byte block.a0, a1 = struct.unpack_from("<BB", block)bits = struct.unpack_from("<6B", block, 2)alphacode1 = (bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24))alphacode2 = bits[0] | (bits[1] << 8)color0, color1 = struct.unpack_from("<HH", block, 8)code, = struct.unpack_from("<I", block, 12)r0, g0, b0 = unpack_565(color0)r1, g1, b1 = unpack_565(color1)for j in range(4):for i in range(4):# get next control op and generate a pixelalphacode_index = 3 * (4 * j + i)if alphacode_index <= 12:alphacode = (alphacode2 >> alphacode_index) & 0x07elif alphacode_index == 15:alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)else: # alphacode_index >= 18 and alphacode_index <= 45alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07if alphacode == 0:a = a0elif alphacode == 1:a = a1elif a0 > a1:a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7elif alphacode == 6:a = 0elif alphacode == 7:a = 255else:a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5color_code = (code >> 2 * (4 * j + i)) & 0x03if color_code == 0:r, g, b = r0, g0, b0elif color_code == 1:r, g, b = r1, g1, b1elif color_code == 2:r = (2 * r0 + r1) // 3g = (2 * g0 + g1) // 3b = (2 * b0 + b1) // 3elif color_code == 3:r = (2 * r1 + r0) // 3g = (2 * g1 + g0) // 3b = (2 * b1 + b0) // 3ret[j].extend([r, g, b, a])return retclass BLPFormatError(NotImplementedError):passclass BlpImageFile(ImageFile.ImageFile):"""Blizzard Mipmap Format"""format = "BLP"format_description = "Blizzard Mipmap Format"def _open(self):self.magic = self.fp.read(4)self._read_blp_header()if self.magic == b"BLP1":decoder = "BLP1"self.mode = "RGB"elif self.magic == b"BLP2":decoder = "BLP2"self.mode = "RGBA" if self._blp_alpha_depth else "RGB"else:raise BLPFormatError("Bad BLP magic %r" % (self.magic))self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]def _read_blp_header(self):self._blp_compression, = struct.unpack("<i", self.fp.read(4))self._blp_encoding, = struct.unpack("<b", self.fp.read(1))self._blp_alpha_depth, = struct.unpack("<b", self.fp.read(1))self._blp_alpha_encoding, = struct.unpack("<b", self.fp.read(1))self._blp_mips, = struct.unpack("<b", self.fp.read(1))self.size = struct.unpack("<II", self.fp.read(8))if self.magic == b"BLP1":# Only present for BLP1self._blp_encoding, = struct.unpack("<i", self.fp.read(4))self._blp_subtype, = struct.unpack("<i", self.fp.read(4))self._blp_offsets = struct.unpack("<16I", self.fp.read(16 * 4))self._blp_lengths = struct.unpack("<16I", self.fp.read(16 * 4))class _BLPBaseDecoder(ImageFile.PyDecoder):_pulls_fd = Truedef decode(self, buffer):try:self.fd.seek(0)self.magic = self.fd.read(4)self._read_blp_header()self._load()except struct.error:raise IOError("Truncated Blp file")return 0, 0def _read_palette(self):ret = []for i in range(256):try:b, g, r, a = struct.unpack("<4B", self.fd.read(4))except struct.error:breakret.append((b, g, r, a))return retdef _read_blp_header(self):self._blp_compression, = struct.unpack("<i", self.fd.read(4))self._blp_encoding, = struct.unpack("<b", self.fd.read(1))self._blp_alpha_depth, = struct.unpack("<b", self.fd.read(1))self._blp_alpha_encoding, = struct.unpack("<b", self.fd.read(1))self._blp_mips, = struct.unpack("<b", self.fd.read(1))self.size = struct.unpack("<II", self.fd.read(8))if self.magic == b"BLP1":# Only present for BLP1self._blp_encoding, = struct.unpack("<i", self.fd.read(4))self._blp_subtype, = struct.unpack("<i", self.fd.read(4))self._blp_offsets = struct.unpack("<16I", self.fd.read(16 * 4))self._blp_lengths = struct.unpack("<16I", self.fd.read(16 * 4))class BLP1Decoder(_BLPBaseDecoder):def _load(self):if self._blp_compression == BLP_FORMAT_JPEG:self._decode_jpeg_stream()elif self._blp_compression == 1:if self._blp_encoding in (4, 5):data = bytearray()palette = self._read_palette()_data = BytesIO(self.fd.read(self._blp_lengths[0]))while True:try:offset, = struct.unpack("<B", _data.read(1))except struct.error:breakb, g, r, a = palette[offset]data.extend([r, g, b])self.set_as_raw(bytes(data))else:raise BLPFormatError("Unsupported BLP encoding %r" % (self._blp_encoding))else:raise BLPFormatError("Unsupported BLP compression %r" % (self._blp_encoding))def _decode_jpeg_stream(self):from PIL.JpegImagePlugin import JpegImageFilejpeg_header_size, = struct.unpack("<I", self.fd.read(4))jpeg_header = self.fd.read(jpeg_header_size)self.fd.read(self._blp_offsets[0] - self.fd.tell()) # What IS this?data = self.fd.read(self._blp_lengths[0])data = jpeg_header + datadata = BytesIO(data)image = JpegImageFile(data)self.tile = image.tile # :/self.fd = image.fpself.mode = image.modeclass BLP2Decoder(_BLPBaseDecoder):def _load(self):palette = self._read_palette()data = bytearray()self.fd.seek(self._blp_offsets[0])if self._blp_compression == 1:# Uncompressed or DirectX compressionif self._blp_encoding == BLP_ENCODING_UNCOMPRESSED:_data = BytesIO(self.fd.read(self._blp_lengths[0]))while True:try:offset, = struct.unpack("<B", _data.read(1))except struct.error:breakb, g, r, a = palette[offset]data.extend((r, g, b))elif self._blp_encoding == BLP_ENCODING_DXT:if self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT1:linesize = (self.size[0] + 3) // 4 * 8for yb in range((self.size[1] + 3) // 4):for d in decode_dxt1(self.fd.read(linesize),alpha=bool(self._blp_alpha_depth)):data += delif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT3:linesize = (self.size[0] + 3) // 4 * 16for yb in range((self.size[1] + 3) // 4):for d in decode_dxt3(self.fd.read(linesize)):data += delif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT5:linesize = (self.size[0] + 3) // 4 * 16for yb in range((self.size[1] + 3) // 4):for d in decode_dxt5(self.fd.read(linesize)):data += delse:raise BLPFormatError("Unsupported alpha encoding %r" % (self._blp_alpha_encoding))else:raise BLPFormatError("Unknown BLP encoding %r" % (self._blp_encoding))else:raise BLPFormatError("Unknown BLP compression %r" % (self._blp_compression))self.set_as_raw(bytes(data))Image.register_open(BlpImageFile.format, BlpImageFile, lambda p: p[:4] in (b"BLP1", b"BLP2"))Image.register_extension(BlpImageFile.format, ".blp")Image.register_decoder("BLP1", BLP1Decoder)Image.register_decoder("BLP2", BLP2Decoder)
123version https://git-lfs.github.com/spec/v1oid sha256:cd0309c97175ba01fd3aa1b53da3606a2d5f087b27db12c8a57d565654396704size 13137123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289## The Python Imaging Library.# $Id$## BMP file handler## Windows (and OS/2) native bitmap storage format.## history:# 1995-09-01 fl Created# 1996-04-30 fl Added save# 1997-08-27 fl Fixed save of 1-bit images# 1998-03-06 fl Load P images as L where possible# 1998-07-03 fl Load P images as 1 where possible# 1998-12-29 fl Handle small palettes# 2002-12-30 fl Fixed load of 1-bit palette images# 2003-04-21 fl Fixed load of 1-bit monochrome images# 2003-04-23 fl Added limited support for BI_BITFIELDS compression## Copyright (c) 1997-2003 by Secret Labs AB# Copyright (c) 1995-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFile, ImagePalettefrom ._binary import i8, i16le as i16, i32le as i32, \o8, o16le as o16, o32le as o32import math__version__ = "0.7"## --------------------------------------------------------------------# Read BMP fileBIT2MODE = {# bits => mode, rawmode1: ("P", "P;1"),4: ("P", "P;4"),8: ("P", "P"),16: ("RGB", "BGR;15"),24: ("RGB", "BGR"),32: ("RGB", "BGRX"),}def _accept(prefix):return prefix[:2] == b"BM"# ==============================================================================# Image plugin for the Windows BMP format.# ==============================================================================class BmpImageFile(ImageFile.ImageFile):""" Image plugin for the Windows Bitmap format (BMP) """# -------------------------------------------------------------- Descriptionformat_description = "Windows Bitmap"format = "BMP"# --------------------------------------------------- BMP Compression valuesCOMPRESSIONS = {'RAW': 0, 'RLE8': 1, 'RLE4': 2, 'BITFIELDS': 3, 'JPEG': 4, 'PNG': 5}RAW, RLE8, RLE4, BITFIELDS, JPEG, PNG = 0, 1, 2, 3, 4, 5def _bitmap(self, header=0, offset=0):""" Read relevant info about the BMP """read, seek = self.fp.read, self.fp.seekif header:seek(header)file_info = {}file_info['header_size'] = i32(read(4)) # read bmp header size @offset 14 (this is part of the header size)file_info['direction'] = -1# --------------------- If requested, read header at a specific positionheader_data = ImageFile._safe_read(self.fp, file_info['header_size'] - 4) # read the rest of the bmp header, without its size# --------------------------------------------------- IBM OS/2 Bitmap v1# ------ This format has different offsets because of width/height typesif file_info['header_size'] == 12:file_info['width'] = i16(header_data[0:2])file_info['height'] = i16(header_data[2:4])file_info['planes'] = i16(header_data[4:6])file_info['bits'] = i16(header_data[6:8])file_info['compression'] = self.RAWfile_info['palette_padding'] = 3# ---------------------------------------------- Windows Bitmap v2 to v5elif file_info['header_size'] in (40, 64, 108, 124): # v3, OS/2 v2, v4, v5if file_info['header_size'] >= 40: # v3 and OS/2file_info['y_flip'] = i8(header_data[7]) == 0xfffile_info['direction'] = 1 if file_info['y_flip'] else -1file_info['width'] = i32(header_data[0:4])file_info['height'] = i32(header_data[4:8]) if not file_info['y_flip'] else 2**32 - i32(header_data[4:8])file_info['planes'] = i16(header_data[8:10])file_info['bits'] = i16(header_data[10:12])file_info['compression'] = i32(header_data[12:16])file_info['data_size'] = i32(header_data[16:20]) # byte size of pixel datafile_info['pixels_per_meter'] = (i32(header_data[20:24]), i32(header_data[24:28]))file_info['colors'] = i32(header_data[28:32])file_info['palette_padding'] = 4self.info["dpi"] = tuple(map(lambda x: int(math.ceil(x / 39.3701)),file_info['pixels_per_meter']))if file_info['compression'] == self.BITFIELDS:if len(header_data) >= 52:for idx, mask in enumerate(['r_mask', 'g_mask', 'b_mask', 'a_mask']):file_info[mask] = i32(header_data[36+idx*4:40+idx*4])else:# 40 byte headers only have the three components in the bitfields masks,# ref: https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376(v=vs.85).aspx# See also https://github.com/python-pillow/Pillow/issues/1293# There is a 4th component in the RGBQuad, in the alpha location, but it# is listed as a reserved component, and it is not generally an alpha channelfile_info['a_mask'] = 0x0for mask in ['r_mask', 'g_mask', 'b_mask']:file_info[mask] = i32(read(4))file_info['rgb_mask'] = (file_info['r_mask'], file_info['g_mask'], file_info['b_mask'])file_info['rgba_mask'] = (file_info['r_mask'], file_info['g_mask'], file_info['b_mask'], file_info['a_mask'])else:raise IOError("Unsupported BMP header type (%d)" % file_info['header_size'])# ------------------ Special case : header is reported 40, which# ---------------------- is shorter than real size for bpp >= 16self.size = file_info['width'], file_info['height']# -------- If color count was not found in the header, compute from bitsfile_info['colors'] = file_info['colors'] if file_info.get('colors', 0) else (1 << file_info['bits'])# -------------------------------- Check abnormal values for DOS attacksif file_info['width'] * file_info['height'] > 2**31:raise IOError("Unsupported BMP Size: (%dx%d)" % self.size)# ----------------------- Check bit depth for unusual unsupported valuesself.mode, raw_mode = BIT2MODE.get(file_info['bits'], (None, None))if self.mode is None:raise IOError("Unsupported BMP pixel depth (%d)" % file_info['bits'])# ----------------- Process BMP with Bitfields compression (not palette)if file_info['compression'] == self.BITFIELDS:SUPPORTED = {32: [(0xff0000, 0xff00, 0xff, 0x0), (0xff0000, 0xff00, 0xff, 0xff000000), (0x0, 0x0, 0x0, 0x0), (0xff000000, 0xff0000, 0xff00, 0x0)],24: [(0xff0000, 0xff00, 0xff)],16: [(0xf800, 0x7e0, 0x1f), (0x7c00, 0x3e0, 0x1f)]}MASK_MODES = {(32, (0xff0000, 0xff00, 0xff, 0x0)): "BGRX",(32, (0xff000000, 0xff0000, 0xff00, 0x0)): "XBGR",(32, (0xff0000, 0xff00, 0xff, 0xff000000)): "BGRA",(32, (0x0, 0x0, 0x0, 0x0)): "BGRA",(24, (0xff0000, 0xff00, 0xff)): "BGR",(16, (0xf800, 0x7e0, 0x1f)): "BGR;16",(16, (0x7c00, 0x3e0, 0x1f)): "BGR;15"}if file_info['bits'] in SUPPORTED:if file_info['bits'] == 32 and file_info['rgba_mask'] in SUPPORTED[file_info['bits']]:raw_mode = MASK_MODES[(file_info['bits'], file_info['rgba_mask'])]self.mode = "RGBA" if raw_mode in ("BGRA",) else self.modeelif file_info['bits'] in (24, 16) and file_info['rgb_mask'] in SUPPORTED[file_info['bits']]:raw_mode = MASK_MODES[(file_info['bits'], file_info['rgb_mask'])]else:raise IOError("Unsupported BMP bitfields layout")else:raise IOError("Unsupported BMP bitfields layout")elif file_info['compression'] == self.RAW:if file_info['bits'] == 32 and header == 22: # 32-bit .cur offsetraw_mode, self.mode = "BGRA", "RGBA"else:raise IOError("Unsupported BMP compression (%d)" % file_info['compression'])# ---------------- Once the header is processed, process the palette/LUTif self.mode == "P": # Paletted for 1, 4 and 8 bit images# ----------------------------------------------------- 1-bit imagesif not (0 < file_info['colors'] <= 65536):raise IOError("Unsupported BMP Palette size (%d)" % file_info['colors'])else:padding = file_info['palette_padding']palette = read(padding * file_info['colors'])greyscale = Trueindices = (0, 255) if file_info['colors'] == 2 else list(range(file_info['colors']))# ------------------ Check if greyscale and ignore palette if sofor ind, val in enumerate(indices):rgb = palette[ind*padding:ind*padding + 3]if rgb != o8(val) * 3:greyscale = False# -------- If all colors are grey, white or black, ditch paletteif greyscale:self.mode = "1" if file_info['colors'] == 2 else "L"raw_mode = self.modeelse:self.mode = "P"self.palette = ImagePalette.raw("BGRX" if padding == 4 else "BGR", palette)# ----------------------------- Finally set the tile data for the pluginself.info['compression'] = file_info['compression']self.tile = [('raw', (0, 0, file_info['width'], file_info['height']), offset or self.fp.tell(),(raw_mode, ((file_info['width'] * file_info['bits'] + 31) >> 3) & (~3), file_info['direction']))]def _open(self):""" Open file, check magic number and read header """# read 14 bytes: magic number, filesize, reserved, header final offsethead_data = self.fp.read(14)# choke if the file does not have the required magic bytesif head_data[0:2] != b"BM":raise SyntaxError("Not a BMP file")# read the start position of the BMP image data (u32)offset = i32(head_data[10:14])# load bitmap information (offset=raster info)self._bitmap(offset=offset)# ==============================================================================# Image plugin for the DIB format (BMP alias)# ==============================================================================class DibImageFile(BmpImageFile):format = "DIB"format_description = "Windows Bitmap"def _open(self):self._bitmap()## --------------------------------------------------------------------# Write BMP fileSAVE = {"1": ("1", 1, 2),"L": ("L", 8, 256),"P": ("P", 8, 256),"RGB": ("BGR", 24, 0),"RGBA": ("BGRA", 32, 0),}def _save(im, fp, filename):try:rawmode, bits, colors = SAVE[im.mode]except KeyError:raise IOError("cannot write mode %s as BMP" % im.mode)info = im.encoderinfodpi = info.get("dpi", (96, 96))# 1 meter == 39.3701 inchesppm = tuple(map(lambda x: int(x * 39.3701), dpi))stride = ((im.size[0]*bits+7)//8+3) & (~3)header = 40 # or 64 for OS/2 version 2offset = 14 + header + colors * 4image = stride * im.size[1]# bitmap headerfp.write(b"BM" + # file type (magic)o32(offset+image) + # file sizeo32(0) + # reservedo32(offset)) # image data offset# bitmap info headerfp.write(o32(header) + # info header sizeo32(im.size[0]) + # widtho32(im.size[1]) + # heighto16(1) + # planeso16(bits) + # deptho32(0) + # compression (0=uncompressed)o32(image) + # size of bitmapo32(ppm[0]) + o32(ppm[1]) + # resolutiono32(colors) + # colors usedo32(colors)) # colors importantfp.write(b"\0" * (header - 40)) # padding (for OS/2 format)if im.mode == "1":for i in (0, 255):fp.write(o8(i) * 4)elif im.mode == "L":for i in range(256):fp.write(o8(i) * 4)elif im.mode == "P":fp.write(im.im.getpalette("RGB", "BGRX"))ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0,(rawmode, stride, -1))])## --------------------------------------------------------------------# RegistryImage.register_open(BmpImageFile.format, BmpImageFile, _accept)Image.register_save(BmpImageFile.format, _save)Image.register_extension(BmpImageFile.format, ".bmp")Image.register_mime(BmpImageFile.format, "image/bmp")
123version https://git-lfs.github.com/spec/v1oid sha256:be59ece47b27acab85a26fb4351fd618baafe64d50d3b0a75429eea777899111size 1518123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172## The Python Imaging Library# $Id$## BUFR stub adapter## Copyright (c) 1996-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFile_handler = Nonedef register_handler(handler):"""Install application-specific BUFR image handler.:param handler: Handler object."""global _handler_handler = handler# --------------------------------------------------------------------# Image adapterdef _accept(prefix):return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC"class BufrStubImageFile(ImageFile.StubImageFile):format = "BUFR"format_description = "BUFR"def _open(self):offset = self.fp.tell()if not _accept(self.fp.read(4)):raise SyntaxError("Not a BUFR file")self.fp.seek(offset)# make something upself.mode = "F"self.size = 1, 1loader = self._load()if loader:loader.open(self)def _load(self):return _handlerdef _save(im, fp, filename):if _handler is None or not hasattr("_handler", "save"):raise IOError("BUFR save handler not installed")_handler.save(im, fp, filename)# --------------------------------------------------------------------# RegistryImage.register_open(BufrStubImageFile.format, BufrStubImageFile, _accept)Image.register_save(BufrStubImageFile.format, _save)Image.register_extension(BufrStubImageFile.format, ".bufr")
123version https://git-lfs.github.com/spec/v1oid sha256:159519950261e88b6b202d16e3c07ca4ec20ab2c19347e185cf1905ea2db89f1size 2693123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116## The Python Imaging Library.# $Id$## a class to read from a container file## History:# 1995-06-18 fl Created# 1995-09-07 fl Added readline(), readlines()## Copyright (c) 1997-2001 by Secret Labs AB# Copyright (c) 1995 by Fredrik Lundh## See the README file for information on usage and redistribution.#### A file object that provides read access to a part of an existing# file (for example a TAR file).class ContainerIO(object):def __init__(self, file, offset, length):"""Create file object.:param file: Existing file.:param offset: Start of region, in bytes.:param length: Size of region, in bytes."""self.fh = fileself.pos = 0self.offset = offsetself.length = lengthself.fh.seek(offset)### Always false.def isatty(self):return 0def seek(self, offset, mode=0):"""Move file pointer.:param offset: Offset in bytes.:param mode: Starting position. Use 0 for beginning of region, 1for current offset, and 2 for end of region. You cannot movethe pointer outside the defined region."""if mode == 1:self.pos = self.pos + offsetelif mode == 2:self.pos = self.length + offsetelse:self.pos = offset# clampself.pos = max(0, min(self.pos, self.length))self.fh.seek(self.offset + self.pos)def tell(self):"""Get current file pointer.:returns: Offset from start of region, in bytes."""return self.posdef read(self, n=0):"""Read data.:param n: Number of bytes to read. If omitted or zero,read until end of region.:returns: An 8-bit string."""if n:n = min(n, self.length - self.pos)else:n = self.length - self.posif not n: # EOFreturn ""self.pos = self.pos + nreturn self.fh.read(n)def readline(self):"""Read a line of text.:returns: An 8-bit string."""s = ""while True:c = self.read(1)if not c:breaks = s + cif c == "\n":breakreturn sdef readlines(self):"""Read multiple lines of text.:returns: A list of 8-bit strings."""l = []while True:s = self.readline()if not s:breakl.append(s)return l
123version https://git-lfs.github.com/spec/v1oid sha256:7deb746cdd95eb6df101b2d3d18333c7c5de14235b1a7b06848fbb481f3cb7b8size 20711234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586## The Python Imaging Library.# $Id$## Windows Cursor support for PIL## notes:# uses BmpImagePlugin.py to read the bitmap data.## history:# 96-05-27 fl Created## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996.## See the README file for information on usage and redistribution.#from __future__ import print_functionfrom . import Image, BmpImagePluginfrom ._binary import i8, i16le as i16, i32le as i32__version__ = "0.1"## --------------------------------------------------------------------def _accept(prefix):return prefix[:4] == b"\0\0\2\0"### Image plugin for Windows Cursor files.class CurImageFile(BmpImagePlugin.BmpImageFile):format = "CUR"format_description = "Windows Cursor"def _open(self):offset = self.fp.tell()# check magics = self.fp.read(6)if not _accept(s):raise SyntaxError("not a CUR file")# pick the largest cursor in the filem = b""for i in range(i16(s[4:])):s = self.fp.read(16)if not m:m = selif i8(s[0]) > i8(m[0]) and i8(s[1]) > i8(m[1]):m = s# print("width", i8(s[0]))# print("height", i8(s[1]))# print("colors", i8(s[2]))# print("reserved", i8(s[3]))# print("hotspot x", i16(s[4:]))# print("hotspot y", i16(s[6:]))# print("bytes", i32(s[8:]))# print("offset", i32(s[12:]))if not m:raise TypeError("No cursors were found")# load as bitmapself._bitmap(i32(m[12:]) + offset)# patch up the bitmap heightself.size = self.size[0], self.size[1]//2d, e, o, a = self.tile[0]self.tile[0] = d, (0, 0)+self.size, o, areturn## --------------------------------------------------------------------Image.register_open(CurImageFile.format, CurImageFile, _accept)Image.register_extension(CurImageFile.format, ".cur")
123version https://git-lfs.github.com/spec/v1oid sha256:1fea54523ade2d5f297228315e2efa5d26860ac7e3ba0655449a63b79c95f5d1size 2025123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687## The Python Imaging Library.# $Id$## DCX file handling## DCX is a container file format defined by Intel, commonly used# for fax applications. Each DCX file consists of a directory# (a list of file offsets) followed by a set of (usually 1-bit)# PCX files.## History:# 1995-09-09 fl Created# 1996-03-20 fl Properly derived from PcxImageFile.# 1998-07-15 fl Renamed offset attribute to avoid name clash# 2002-07-30 fl Fixed file handling## Copyright (c) 1997-98 by Secret Labs AB.# Copyright (c) 1995-96 by Fredrik Lundh.## See the README file for information on usage and redistribution.#from . import Imagefrom ._binary import i32le as i32from .PcxImagePlugin import PcxImageFile__version__ = "0.2"MAGIC = 0x3ADE68B1 # QUIZ: what's this value, then?def _accept(prefix):return len(prefix) >= 4 and i32(prefix) == MAGIC### Image plugin for the Intel DCX format.class DcxImageFile(PcxImageFile):format = "DCX"format_description = "Intel DCX"_close_exclusive_fp_after_loading = Falsedef _open(self):# Headers = self.fp.read(4)if i32(s) != MAGIC:raise SyntaxError("not a DCX file")# Component directoryself._offset = []for i in range(1024):offset = i32(self.fp.read(4))if not offset:breakself._offset.append(offset)self.__fp = self.fpself.frame = Noneself.seek(0)@propertydef n_frames(self):return len(self._offset)@propertydef is_animated(self):return len(self._offset) > 1def seek(self, frame):if not self._seek_check(frame):returnself.frame = frameself.fp = self.__fpself.fp.seek(self._offset[frame])PcxImageFile._open(self)def tell(self):return self.frameImage.register_open(DcxImageFile.format, DcxImageFile, _accept)Image.register_extension(DcxImageFile.format, ".dcx")
123version https://git-lfs.github.com/spec/v1oid sha256:86d83d2e6cec12c85afcd8318549503600f0fc2a7b609308993439be51283f17size 5040123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""A Pillow loader for .dds files (S3TC-compressed aka DXTC)Jerome Leclanche <jerome@leclan.ch>Documentation:https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txtThe contents of this file are hereby released in the public domain (CC0)Full text of the CC0 license:https://creativecommons.org/publicdomain/zero/1.0/"""import structfrom io import BytesIOfrom . import Image, ImageFile# Magic ("DDS ")DDS_MAGIC = 0x20534444# DDS flagsDDSD_CAPS = 0x1DDSD_HEIGHT = 0x2DDSD_WIDTH = 0x4DDSD_PITCH = 0x8DDSD_PIXELFORMAT = 0x1000DDSD_MIPMAPCOUNT = 0x20000DDSD_LINEARSIZE = 0x80000DDSD_DEPTH = 0x800000# DDS capsDDSCAPS_COMPLEX = 0x8DDSCAPS_TEXTURE = 0x1000DDSCAPS_MIPMAP = 0x400000DDSCAPS2_CUBEMAP = 0x200DDSCAPS2_CUBEMAP_POSITIVEX = 0x400DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000DDSCAPS2_VOLUME = 0x200000# Pixel FormatDDPF_ALPHAPIXELS = 0x1DDPF_ALPHA = 0x2DDPF_FOURCC = 0x4DDPF_PALETTEINDEXED8 = 0x20DDPF_RGB = 0x40DDPF_LUMINANCE = 0x20000# dds.hDDS_FOURCC = DDPF_FOURCCDDS_RGB = DDPF_RGBDDS_RGBA = DDPF_RGB | DDPF_ALPHAPIXELSDDS_LUMINANCE = DDPF_LUMINANCEDDS_LUMINANCEA = DDPF_LUMINANCE | DDPF_ALPHAPIXELSDDS_ALPHA = DDPF_ALPHADDS_PAL8 = DDPF_PALETTEINDEXED8DDS_HEADER_FLAGS_TEXTURE = (DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH |DDSD_PIXELFORMAT)DDS_HEADER_FLAGS_MIPMAP = DDSD_MIPMAPCOUNTDDS_HEADER_FLAGS_VOLUME = DDSD_DEPTHDDS_HEADER_FLAGS_PITCH = DDSD_PITCHDDS_HEADER_FLAGS_LINEARSIZE = DDSD_LINEARSIZEDDS_HEIGHT = DDSD_HEIGHTDDS_WIDTH = DDSD_WIDTHDDS_SURFACE_FLAGS_TEXTURE = DDSCAPS_TEXTUREDDS_SURFACE_FLAGS_MIPMAP = DDSCAPS_COMPLEX | DDSCAPS_MIPMAPDDS_SURFACE_FLAGS_CUBEMAP = DDSCAPS_COMPLEXDDS_CUBEMAP_POSITIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEXDDS_CUBEMAP_NEGATIVEX = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEXDDS_CUBEMAP_POSITIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEYDDS_CUBEMAP_NEGATIVEY = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEYDDS_CUBEMAP_POSITIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_POSITIVEZDDS_CUBEMAP_NEGATIVEZ = DDSCAPS2_CUBEMAP | DDSCAPS2_CUBEMAP_NEGATIVEZ# DXT1DXT1_FOURCC = 0x31545844# DXT3DXT3_FOURCC = 0x33545844# DXT5DXT5_FOURCC = 0x35545844# dxgiformat.hDXGI_FORMAT_BC7_TYPELESS = 97DXGI_FORMAT_BC7_UNORM = 98DXGI_FORMAT_BC7_UNORM_SRGB = 99class DdsImageFile(ImageFile.ImageFile):format = "DDS"format_description = "DirectDraw Surface"def _open(self):magic, header_size = struct.unpack("<II", self.fp.read(8))if header_size != 124:raise IOError("Unsupported header size %r" % (header_size))header_bytes = self.fp.read(header_size - 4)if len(header_bytes) != 120:raise IOError("Incomplete header: %s bytes" % len(header_bytes))header = BytesIO(header_bytes)flags, height, width = struct.unpack("<3I", header.read(12))self.size = (width, height)self.mode = "RGBA"pitch, depth, mipmaps = struct.unpack("<3I", header.read(12))reserved = struct.unpack("<11I", header.read(44))# pixel formatpfsize, pfflags = struct.unpack("<2I", header.read(8))fourcc = header.read(4)bitcount, rmask, gmask, bmask, amask = struct.unpack("<5I",header.read(20))data_start = header_size + 4n = 0if fourcc == b"DXT1":self.pixel_format = "DXT1"n = 1elif fourcc == b"DXT3":self.pixel_format = "DXT3"n = 2elif fourcc == b"DXT5":self.pixel_format = "DXT5"n = 3elif fourcc == b"DX10":data_start += 20# ignoring flags which pertain to volume textures and cubemapsdxt10 = BytesIO(self.fp.read(20))dxgi_format, dimension = struct.unpack("<II", dxt10.read(8))if dxgi_format in (DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM):self.pixel_format = "BC7"n = 7elif dxgi_format == DXGI_FORMAT_BC7_UNORM_SRGB:self.pixel_format = "BC7"self.im_info["gamma"] = 1/2.2n = 7else:raise NotImplementedError("Unimplemented DXGI format %d" %(dxgi_format))else:raise NotImplementedError("Unimplemented pixel format %r" %(fourcc))self.tile = [("bcn", (0, 0) + self.size, data_start, (n))]def load_seek(self, pos):passdef _validate(prefix):return prefix[:4] == b"DDS "Image.register_open(DdsImageFile.format, DdsImageFile, _validate)Image.register_extension(DdsImageFile.format, ".dds")
123version https://git-lfs.github.com/spec/v1oid sha256:addea307c55868bef8d5fcce3ad83b352047ceff0df3f68bd730c7bfc599e433size 12883123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429## The Python Imaging Library.# $Id$## EPS file handling## History:# 1995-09-01 fl Created (0.1)# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)# 1996-08-22 fl Don't choke on floating point BoundingBox values# 1996-08-23 fl Handle files from Macintosh (0.3)# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)# 2014-05-07 e Handling of EPS with binary preview and fixed resolution# resizing## Copyright (c) 1997-2003 by Secret Labs AB.# Copyright (c) 1995-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#import reimport ioimport osimport sysfrom . import Image, ImageFilefrom ._binary import i32le as i32from ._util import py3__version__ = "0.5"## --------------------------------------------------------------------split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")gs_windows_binary = Noneif sys.platform.startswith('win'):import shutilif hasattr(shutil, 'which'):which = shutil.whichelse:# Python < 3.3import distutils.spawnwhich = distutils.spawn.find_executablefor binary in ('gswin32c', 'gswin64c', 'gs'):if which(binary) is not None:gs_windows_binary = binarybreakelse:gs_windows_binary = Falsedef has_ghostscript():if gs_windows_binary:return Trueif not sys.platform.startswith('win'):import subprocesstry:with open(os.devnull, 'wb') as devnull:subprocess.check_call(['gs', '--version'], stdout=devnull)return Trueexcept OSError:# no ghostscriptpassreturn Falsedef Ghostscript(tile, size, fp, scale=1):"""Render an image using Ghostscript"""# Unpack decoder tiledecoder, tile, offset, data = tile[0]length, bbox = data# Hack to support hi-res renderingscale = int(scale) or 1# orig_size = size# orig_bbox = bboxsize = (size[0] * scale, size[1] * scale)# resolution is dependent on bbox and sizeres = (float((72.0 * size[0]) / (bbox[2]-bbox[0])),float((72.0 * size[1]) / (bbox[3]-bbox[1])))# print("Ghostscript", scale, size, orig_size, bbox, orig_bbox, res)import subprocessimport tempfileout_fd, outfile = tempfile.mkstemp()os.close(out_fd)infile_temp = Noneif hasattr(fp, 'name') and os.path.exists(fp.name):infile = fp.nameelse:in_fd, infile_temp = tempfile.mkstemp()os.close(in_fd)infile = infile_temp# ignore length and offset!# ghostscript can read it# copy whole file to read in ghostscriptwith open(infile_temp, 'wb') as f:# fetch length of fpfp.seek(0, 2)fsize = fp.tell()# ensure start position# go backfp.seek(0)lengthfile = fsizewhile lengthfile > 0:s = fp.read(min(lengthfile, 100*1024))if not s:breaklengthfile -= len(s)f.write(s)# Build ghostscript commandcommand = ["gs","-q", # quiet mode"-g%dx%d" % size, # set output geometry (pixels)"-r%fx%f" % res, # set input DPI (dots per inch)"-dBATCH", # exit after processing"-dNOPAUSE", # don't pause between pages,"-dSAFER", # safe mode"-sDEVICE=ppmraw", # ppm driver"-sOutputFile=%s" % outfile, # output file"-c", "%d %d translate" % (-bbox[0], -bbox[1]),# adjust for image origin"-f", infile, # input file"-c", "showpage", # showpage (see: https://bugs.ghostscript.com/show_bug.cgi?id=698272)]if gs_windows_binary is not None:if not gs_windows_binary:raise WindowsError('Unable to locate Ghostscript on paths')command[0] = gs_windows_binary# push data through ghostscripttry:with open(os.devnull, 'w+b') as devnull:subprocess.check_call(command, stdin=devnull, stdout=devnull)im = Image.open(outfile)im.load()finally:try:os.unlink(outfile)if infile_temp:os.unlink(infile_temp)except OSError:passreturn im.im.copy()class PSFile(object):"""Wrapper for bytesio object that treats either CR or LF as end of line."""def __init__(self, fp):self.fp = fpself.char = Nonedef seek(self, offset, whence=0):self.char = Noneself.fp.seek(offset, whence)def readline(self):s = self.char or b""self.char = Nonec = self.fp.read(1)while c not in b"\r\n":s = s + cc = self.fp.read(1)self.char = self.fp.read(1)# line endings can be 1 or 2 of \r \n, in either orderif self.char in b"\r\n":self.char = Nonereturn s.decode('latin-1')def _accept(prefix):return prefix[:4] == b"%!PS" or \(len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5)### Image plugin for Encapsulated Postscript. This plugin supports only# a few variants of this format.class EpsImageFile(ImageFile.ImageFile):"""EPS File Parser for the Python Imaging Library"""format = "EPS"format_description = "Encapsulated Postscript"mode_map = {1: "L", 2: "LAB", 3: "RGB", 4: "CMYK"}def _open(self):(length, offset) = self._find_offset(self.fp)# Rewrap the open file pointer in something that will# convert line endings and decode to latin-1.try:if py3:# Python3, can use bare open command.fp = open(self.fp.name, "Ur", encoding='latin-1')else:# Python2, no encoding conversion necessaryfp = open(self.fp.name, "Ur")except:# Expect this for bytesio/stringiofp = PSFile(self.fp)# go to offset - start of "%!PS"fp.seek(offset)box = Noneself.mode = "RGB"self.size = 1, 1 # FIXME: huh?## Load EPS headers_raw = fp.readline()s = s_raw.strip('\r\n')while s_raw:if s:if len(s) > 255:raise SyntaxError("not an EPS file")try:m = split.match(s)except re.error as v:raise SyntaxError("not an EPS file")if m:k, v = m.group(1, 2)self.info[k] = vif k == "BoundingBox":try:# Note: The DSC spec says that BoundingBox# fields should be integers, but some drivers# put floating point values there anyway.box = [int(float(i)) for i in v.split()]self.size = box[2] - box[0], box[3] - box[1]self.tile = [("eps", (0, 0) + self.size, offset,(length, box))]except:passelse:m = field.match(s)if m:k = m.group(1)if k == "EndComments":breakif k[:8] == "PS-Adobe":self.info[k[:8]] = k[9:]else:self.info[k] = ""elif s[0] == '%':# handle non-DSC Postscript comments that some# tools mistakenly put in the Comments sectionpasselse:raise IOError("bad EPS header")s_raw = fp.readline()s = s_raw.strip('\r\n')if s and s[:1] != "%":break## Scan for an "ImageData" descriptorwhile s[:1] == "%":if len(s) > 255:raise SyntaxError("not an EPS file")if s[:11] == "%ImageData:":# Encoded bitmapped image.x, y, bi, mo = s[11:].split(None, 7)[:4]if int(bi) != 8:breaktry:self.mode = self.mode_map[int(mo)]except ValueError:breakself.size = int(x), int(y)returns = fp.readline().strip('\r\n')if not s:breakif not box:raise IOError("cannot determine EPS bounding box")def _find_offset(self, fp):s = fp.read(160)if s[:4] == b"%!PS":# for HEAD without binary previewfp.seek(0, 2)length = fp.tell()offset = 0elif i32(s[0:4]) == 0xC6D3D0C5:# FIX for: Some EPS file not handled correctly / issue #302# EPS can contain binary data# or start directly with latin coding# more info see:# https://web.archive.org/web/20160528181353/http://partners.adobe.com/public/developer/en/ps/5002.EPSF_Spec.pdfoffset = i32(s[4:8])length = i32(s[8:12])else:raise SyntaxError("not an EPS file")return (length, offset)def load(self, scale=1):# Load EPS via Ghostscriptif not self.tile:returnself.im = Ghostscript(self.tile, self.size, self.fp, scale)self.mode = self.im.modeself.size = self.im.sizeself.tile = []def load_seek(self, *args, **kwargs):# we can't incrementally load, so force ImageFile.parser to# use our custom load method by defining this method.pass## --------------------------------------------------------------------def _save(im, fp, filename, eps=1):"""EPS Writer for the Python Imaging Library."""## make sure image data is availableim.load()## determine postscript image modeif im.mode == "L":operator = (8, 1, "image")elif im.mode == "RGB":operator = (8, 3, "false 3 colorimage")elif im.mode == "CMYK":operator = (8, 4, "false 4 colorimage")else:raise ValueError("image mode is not supported")class NoCloseStream(object):def __init__(self, fp):self.fp = fpdef __getattr__(self, name):return getattr(self.fp, name)def close(self):passbase_fp = fpif fp != sys.stdout:fp = NoCloseStream(fp)if sys.version_info.major > 2:fp = io.TextIOWrapper(fp, encoding='latin-1')if eps:## write EPS headerfp.write("%!PS-Adobe-3.0 EPSF-3.0\n")fp.write("%%Creator: PIL 0.1 EpsEncode\n")# fp.write("%%CreationDate: %s"...)fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size)fp.write("%%Pages: 1\n")fp.write("%%EndComments\n")fp.write("%%Page: 1 1\n")fp.write("%%ImageData: %d %d " % im.size)fp.write("%d %d 0 1 1 \"%s\"\n" % operator)## image headerfp.write("gsave\n")fp.write("10 dict begin\n")fp.write("/buf %d string def\n" % (im.size[0] * operator[1]))fp.write("%d %d scale\n" % im.size)fp.write("%d %d 8\n" % im.size) # <= bitsfp.write("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))fp.write("{ currentfile buf readhexstring pop } bind\n")fp.write(operator[2] + "\n")if hasattr(fp, "flush"):fp.flush()ImageFile._save(im, base_fp, [("eps", (0, 0)+im.size, 0, None)])fp.write("\n%%%%EndBinary\n")fp.write("grestore end\n")if hasattr(fp, "flush"):fp.flush()## --------------------------------------------------------------------Image.register_open(EpsImageFile.format, EpsImageFile, _accept)Image.register_save(EpsImageFile.format, _save)Image.register_extensions(EpsImageFile.format, [".ps", ".eps"])Image.register_mime(EpsImageFile.format, "application/postscript")
123version https://git-lfs.github.com/spec/v1oid sha256:f80bb087e8678693ae042a3a496e611264e825899b8dab75dd34c6e0e9c5f50esize 8837123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315## The Python Imaging Library.# $Id$## EXIF tags## Copyright (c) 2003 by Secret Labs AB## See the README file for information on usage and redistribution.#### This module provides constants and clear-text names for various# well-known EXIF tags.##### Maps EXIF tags to tag names.TAGS = {# possibly incomplete0x000b: "ProcessingSoftware",0x00fe: "NewSubfileType",0x00ff: "SubfileType",0x0100: "ImageWidth",0x0101: "ImageLength",0x0102: "BitsPerSample",0x0103: "Compression",0x0106: "PhotometricInterpretation",0x0107: "Thresholding",0x0108: "CellWidth",0x0109: "CellLength",0x010a: "FillOrder",0x010d: "DocumentName",0x010e: "ImageDescription",0x010f: "Make",0x0110: "Model",0x0111: "StripOffsets",0x0112: "Orientation",0x0115: "SamplesPerPixel",0x0116: "RowsPerStrip",0x0117: "StripByteCounts",0x0118: "MinSampleValue",0x0119: "MaxSampleValue",0x011a: "XResolution",0x011b: "YResolution",0x011c: "PlanarConfiguration",0x011d: "PageName",0x0120: "FreeOffsets",0x0121: "FreeByteCounts",0x0122: "GrayResponseUnit",0x0123: "GrayResponseCurve",0x0124: "T4Options",0x0125: "T6Options",0x0128: "ResolutionUnit",0x0129: "PageNumber",0x012d: "TransferFunction",0x0131: "Software",0x0132: "DateTime",0x013b: "Artist",0x013c: "HostComputer",0x013d: "Predictor",0x013e: "WhitePoint",0x013f: "PrimaryChromaticities",0x0140: "ColorMap",0x0141: "HalftoneHints",0x0142: "TileWidth",0x0143: "TileLength",0x0144: "TileOffsets",0x0145: "TileByteCounts",0x014a: "SubIFDs",0x014c: "InkSet",0x014d: "InkNames",0x014e: "NumberOfInks",0x0150: "DotRange",0x0151: "TargetPrinter",0x0152: "ExtraSamples",0x0153: "SampleFormat",0x0154: "SMinSampleValue",0x0155: "SMaxSampleValue",0x0156: "TransferRange",0x0157: "ClipPath",0x0158: "XClipPathUnits",0x0159: "YClipPathUnits",0x015a: "Indexed",0x015b: "JPEGTables",0x015f: "OPIProxy",0x0200: "JPEGProc",0x0201: "JpegIFOffset",0x0202: "JpegIFByteCount",0x0203: "JpegRestartInterval",0x0205: "JpegLosslessPredictors",0x0206: "JpegPointTransforms",0x0207: "JpegQTables",0x0208: "JpegDCTables",0x0209: "JpegACTables",0x0211: "YCbCrCoefficients",0x0212: "YCbCrSubSampling",0x0213: "YCbCrPositioning",0x0214: "ReferenceBlackWhite",0x02bc: "XMLPacket",0x1000: "RelatedImageFileFormat",0x1001: "RelatedImageWidth",0x1002: "RelatedImageLength",0x4746: "Rating",0x4749: "RatingPercent",0x800d: "ImageID",0x828d: "CFARepeatPatternDim",0x828e: "CFAPattern",0x828f: "BatteryLevel",0x8298: "Copyright",0x829a: "ExposureTime",0x829d: "FNumber",0x83bb: "IPTCNAA",0x8649: "ImageResources",0x8769: "ExifOffset",0x8773: "InterColorProfile",0x8822: "ExposureProgram",0x8824: "SpectralSensitivity",0x8825: "GPSInfo",0x8827: "ISOSpeedRatings",0x8828: "OECF",0x8829: "Interlace",0x882a: "TimeZoneOffset",0x882b: "SelfTimerMode",0x9000: "ExifVersion",0x9003: "DateTimeOriginal",0x9004: "DateTimeDigitized",0x9101: "ComponentsConfiguration",0x9102: "CompressedBitsPerPixel",0x9201: "ShutterSpeedValue",0x9202: "ApertureValue",0x9203: "BrightnessValue",0x9204: "ExposureBiasValue",0x9205: "MaxApertureValue",0x9206: "SubjectDistance",0x9207: "MeteringMode",0x9208: "LightSource",0x9209: "Flash",0x920a: "FocalLength",0x920b: "FlashEnergy",0x920c: "SpatialFrequencyResponse",0x920d: "Noise",0x9211: "ImageNumber",0x9212: "SecurityClassification",0x9213: "ImageHistory",0x9214: "SubjectLocation",0x9215: "ExposureIndex",0x9216: "TIFF/EPStandardID",0x927c: "MakerNote",0x9286: "UserComment",0x9290: "SubsecTime",0x9291: "SubsecTimeOriginal",0x9292: "SubsecTimeDigitized",0x9c9b: "XPTitle",0x9c9c: "XPComment",0x9c9d: "XPAuthor",0x9c9e: "XPKeywords",0x9c9f: "XPSubject",0xa000: "FlashPixVersion",0xa001: "ColorSpace",0xa002: "ExifImageWidth",0xa003: "ExifImageHeight",0xa004: "RelatedSoundFile",0xa005: "ExifInteroperabilityOffset",0xa20b: "FlashEnergy",0xa20c: "SpatialFrequencyResponse",0xa20e: "FocalPlaneXResolution",0xa20f: "FocalPlaneYResolution",0xa210: "FocalPlaneResolutionUnit",0xa214: "SubjectLocation",0xa215: "ExposureIndex",0xa217: "SensingMethod",0xa300: "FileSource",0xa301: "SceneType",0xa302: "CFAPattern",0xa401: "CustomRendered",0xa402: "ExposureMode",0xa403: "WhiteBalance",0xa404: "DigitalZoomRatio",0xa405: "FocalLengthIn35mmFilm",0xa406: "SceneCaptureType",0xa407: "GainControl",0xa408: "Contrast",0xa409: "Saturation",0xa40a: "Sharpness",0xa40b: "DeviceSettingDescription",0xa40c: "SubjectDistanceRange",0xa420: "ImageUniqueID",0xa430: "CameraOwnerName",0xa431: "BodySerialNumber",0xa432: "LensSpecification",0xa433: "LensMake",0xa434: "LensModel",0xa435: "LensSerialNumber",0xa500: "Gamma",0xc4a5: "PrintImageMatching",0xc612: "DNGVersion",0xc613: "DNGBackwardVersion",0xc614: "UniqueCameraModel",0xc615: "LocalizedCameraModel",0xc616: "CFAPlaneColor",0xc617: "CFALayout",0xc618: "LinearizationTable",0xc619: "BlackLevelRepeatDim",0xc61a: "BlackLevel",0xc61b: "BlackLevelDeltaH",0xc61c: "BlackLevelDeltaV",0xc61d: "WhiteLevel",0xc61e: "DefaultScale",0xc61f: "DefaultCropOrigin",0xc620: "DefaultCropSize",0xc621: "ColorMatrix1",0xc622: "ColorMatrix2",0xc623: "CameraCalibration1",0xc624: "CameraCalibration2",0xc625: "ReductionMatrix1",0xc626: "ReductionMatrix2",0xc627: "AnalogBalance",0xc628: "AsShotNeutral",0xc629: "AsShotWhiteXY",0xc62a: "BaselineExposure",0xc62b: "BaselineNoise",0xc62c: "BaselineSharpness",0xc62d: "BayerGreenSplit",0xc62e: "LinearResponseLimit",0xc62f: "CameraSerialNumber",0xc630: "LensInfo",0xc631: "ChromaBlurRadius",0xc632: "AntiAliasStrength",0xc633: "ShadowScale",0xc634: "DNGPrivateData",0xc635: "MakerNoteSafety",0xc65a: "CalibrationIlluminant1",0xc65b: "CalibrationIlluminant2",0xc65c: "BestQualityScale",0xc65d: "RawDataUniqueID",0xc68b: "OriginalRawFileName",0xc68c: "OriginalRawFileData",0xc68d: "ActiveArea",0xc68e: "MaskedAreas",0xc68f: "AsShotICCProfile",0xc690: "AsShotPreProfileMatrix",0xc691: "CurrentICCProfile",0xc692: "CurrentPreProfileMatrix",0xc6bf: "ColorimetricReference",0xc6f3: "CameraCalibrationSignature",0xc6f4: "ProfileCalibrationSignature",0xc6f6: "AsShotProfileName",0xc6f7: "NoiseReductionApplied",0xc6f8: "ProfileName",0xc6f9: "ProfileHueSatMapDims",0xc6fa: "ProfileHueSatMapData1",0xc6fb: "ProfileHueSatMapData2",0xc6fc: "ProfileToneCurve",0xc6fd: "ProfileEmbedPolicy",0xc6fe: "ProfileCopyright",0xc714: "ForwardMatrix1",0xc715: "ForwardMatrix2",0xc716: "PreviewApplicationName",0xc717: "PreviewApplicationVersion",0xc718: "PreviewSettingsName",0xc719: "PreviewSettingsDigest",0xc71a: "PreviewColorSpace",0xc71b: "PreviewDateTime",0xc71c: "RawImageDigest",0xc71d: "OriginalRawFileDigest",0xc71e: "SubTileBlockSize",0xc71f: "RowInterleaveFactor",0xc725: "ProfileLookTableDims",0xc726: "ProfileLookTableData",0xc740: "OpcodeList1",0xc741: "OpcodeList2",0xc74e: "OpcodeList3",0xc761: "NoiseProfile"}### Maps EXIF GPS tags to tag names.GPSTAGS = {0: "GPSVersionID",1: "GPSLatitudeRef",2: "GPSLatitude",3: "GPSLongitudeRef",4: "GPSLongitude",5: "GPSAltitudeRef",6: "GPSAltitude",7: "GPSTimeStamp",8: "GPSSatellites",9: "GPSStatus",10: "GPSMeasureMode",11: "GPSDOP",12: "GPSSpeedRef",13: "GPSSpeed",14: "GPSTrackRef",15: "GPSTrack",16: "GPSImgDirectionRef",17: "GPSImgDirection",18: "GPSMapDatum",19: "GPSDestLatitudeRef",20: "GPSDestLatitude",21: "GPSDestLongitudeRef",22: "GPSDestLongitude",23: "GPSDestBearingRef",24: "GPSDestBearing",25: "GPSDestDistanceRef",26: "GPSDestDistance",27: "GPSProcessingMethod",28: "GPSAreaInformation",29: "GPSDateStamp",30: "GPSDifferential",31: "GPSHPositioningError",}
123version https://git-lfs.github.com/spec/v1oid sha256:fa48d56c64e384ab95826bda1abc85c97100d0b666ed6a1f1fb7f4c91f708972size 1622123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475## The Python Imaging Library# $Id$## FITS stub adapter## Copyright (c) 1998-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFile_handler = Nonedef register_handler(handler):"""Install application-specific FITS image handler.:param handler: Handler object."""global _handler_handler = handler# --------------------------------------------------------------------# Image adapterdef _accept(prefix):return prefix[:6] == b"SIMPLE"class FITSStubImageFile(ImageFile.StubImageFile):format = "FITS"format_description = "FITS"def _open(self):offset = self.fp.tell()if not _accept(self.fp.read(6)):raise SyntaxError("Not a FITS file")# FIXME: add more sanity checks here; mandatory header items# include SIMPLE, BITPIX, NAXIS, etc.self.fp.seek(offset)# make something upself.mode = "F"self.size = 1, 1loader = self._load()if loader:loader.open(self)def _load(self):return _handlerdef _save(im, fp, filename):if _handler is None or not hasattr("_handler", "save"):raise IOError("FITS save handler not installed")_handler.save(im, fp, filename)# --------------------------------------------------------------------# RegistryImage.register_open(FITSStubImageFile.format, FITSStubImageFile, _accept)Image.register_save(FITSStubImageFile.format, _save)Image.register_extensions(FITSStubImageFile.format, [".fit", ".fits"])
123version https://git-lfs.github.com/spec/v1oid sha256:11fe00d260986e4d9c5bb8d6ce9f6c7e90953802e08ecd5125ec82a62dbcaec3size 4093123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163## The Python Imaging Library.# $Id$## FLI/FLC file handling.## History:# 95-09-01 fl Created# 97-01-03 fl Fixed parser, setup decoder tile# 98-07-15 fl Renamed offset attribute to avoid name clash## Copyright (c) Secret Labs AB 1997-98.# Copyright (c) Fredrik Lundh 1995-97.## See the README file for information on usage and redistribution.#from . import Image, ImageFile, ImagePalettefrom ._binary import i8, i16le as i16, i32le as i32, o8__version__ = "0.2"## decoderdef _accept(prefix):return len(prefix) >= 6 and i16(prefix[4:6]) in [0xAF11, 0xAF12]### Image plugin for the FLI/FLC animation format. Use the <b>seek</b># method to load individual frames.class FliImageFile(ImageFile.ImageFile):format = "FLI"format_description = "Autodesk FLI/FLC Animation"_close_exclusive_fp_after_loading = Falsedef _open(self):# HEADs = self.fp.read(128)magic = i16(s[4:6])if not (magic in [0xAF11, 0xAF12] andi16(s[14:16]) in [0, 3] and # flagss[20:22] == b"\x00\x00"): # reservedraise SyntaxError("not an FLI/FLC file")# framesself.__framecount = i16(s[6:8])# image characteristicsself.mode = "P"self.size = i16(s[8:10]), i16(s[10:12])# animation speedduration = i32(s[16:20])if magic == 0xAF11:duration = (duration * 1000) // 70self.info["duration"] = duration# look for palettepalette = [(a, a, a) for a in range(256)]s = self.fp.read(16)self.__offset = 128if i16(s[4:6]) == 0xF100:# prefix chunk; ignore itself.__offset = self.__offset + i32(s)s = self.fp.read(16)if i16(s[4:6]) == 0xF1FA:# look for palette chunks = self.fp.read(6)if i16(s[4:6]) == 11:self._palette(palette, 2)elif i16(s[4:6]) == 4:self._palette(palette, 0)palette = [o8(r)+o8(g)+o8(b) for (r, g, b) in palette]self.palette = ImagePalette.raw("RGB", b"".join(palette))# set things up to decode first frameself.__frame = -1self.__fp = self.fpself.__rewind = self.fp.tell()self.seek(0)def _palette(self, palette, shift):# load palettei = 0for e in range(i16(self.fp.read(2))):s = self.fp.read(2)i = i + i8(s[0])n = i8(s[1])if n == 0:n = 256s = self.fp.read(n * 3)for n in range(0, len(s), 3):r = i8(s[n]) << shiftg = i8(s[n+1]) << shiftb = i8(s[n+2]) << shiftpalette[i] = (r, g, b)i += 1@propertydef n_frames(self):return self.__framecount@propertydef is_animated(self):return self.__framecount > 1def seek(self, frame):if not self._seek_check(frame):returnif frame < self.__frame:self._seek(0)for f in range(self.__frame + 1, frame + 1):self._seek(f)def _seek(self, frame):if frame == 0:self.__frame = -1self.__fp.seek(self.__rewind)self.__offset = 128if frame != self.__frame + 1:raise ValueError("cannot seek to frame %d" % frame)self.__frame = frame# move to next frameself.fp = self.__fpself.fp.seek(self.__offset)s = self.fp.read(4)if not s:raise EOFErrorframesize = i32(s)self.decodermaxblock = framesizeself.tile = [("fli", (0, 0)+self.size, self.__offset, None)]self.__offset += framesizedef tell(self):return self.__frame## registryImage.register_open(FliImageFile.format, FliImageFile, _accept)Image.register_extensions(FliImageFile.format, [".fli", ".flc"])
123version https://git-lfs.github.com/spec/v1oid sha256:aff23bc846351867e022fd25d808732cd02344e5936a5884cec8e6030153d0a7size 2840123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114## The Python Imaging Library# $Id$## base class for raster font file parsers## history:# 1997-06-05 fl created# 1997-08-19 fl restrict image width## Copyright (c) 1997-1998 by Secret Labs AB# Copyright (c) 1997-1998 by Fredrik Lundh## See the README file for information on usage and redistribution.#from __future__ import print_functionimport osfrom . import Image, _binaryWIDTH = 800def puti16(fp, values):# write network order (big-endian) 16-bit sequencefor v in values:if v < 0:v += 65536fp.write(_binary.o16be(v))### Base class for raster font file handlers.class FontFile(object):bitmap = Nonedef __init__(self):self.info = {}self.glyph = [None] * 256def __getitem__(self, ix):return self.glyph[ix]def compile(self):"Create metrics and bitmap"if self.bitmap:return# create bitmap large enough to hold all datah = w = maxwidth = 0lines = 1for glyph in self:if glyph:d, dst, src, im = glyphh = max(h, src[3] - src[1])w = w + (src[2] - src[0])if w > WIDTH:lines += 1w = (src[2] - src[0])maxwidth = max(maxwidth, w)xsize = maxwidthysize = lines * hif xsize == 0 and ysize == 0:return ""self.ysize = h# paste glyphs into bitmapself.bitmap = Image.new("1", (xsize, ysize))self.metrics = [None] * 256x = y = 0for i in range(256):glyph = self[i]if glyph:d, dst, src, im = glyphxx = src[2] - src[0]# yy = src[3] - src[1]x0, y0 = x, yx = x + xxif x > WIDTH:x, y = 0, y + hx0, y0 = x, yx = xxs = src[0] + x0, src[1] + y0, src[2] + x0, src[3] + y0self.bitmap.paste(im.crop(src), s)# print(chr(i), dst, s)self.metrics[i] = d, dst, sdef save(self, filename):"Save font"self.compile()# font dataself.bitmap.save(os.path.splitext(filename)[0] + ".pbm", "PNG")# font metricswith open(os.path.splitext(filename)[0] + ".pil", "wb") as fp:fp.write(b"PILfont\n")fp.write((";;;;;;%d;\n" % self.ysize).encode('ascii')) # HACK!!!fp.write(b"DATA\n")for id in range(256):m = self.metrics[id]if not m:puti16(fp, [0] * 10)else:puti16(fp, m[0] + m[1] + m[2])
123version https://git-lfs.github.com/spec/v1oid sha256:88827c42a3a9f46947add14d66011d933cce0326c7bdf09d1cf6e0937793893fsize 6379123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229## THIS IS WORK IN PROGRESS## The Python Imaging Library.# $Id$## FlashPix support for PIL## History:# 97-01-25 fl Created (reads uncompressed RGB images only)## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1997.## See the README file for information on usage and redistribution.#from __future__ import print_functionfrom . import Image, ImageFilefrom ._binary import i32le as i32, i8import olefile__version__ = "0.1"# we map from colour field tuples to (mode, rawmode) descriptorsMODES = {# opacity(0x00007ffe): ("A", "L"),# monochrome(0x00010000,): ("L", "L"),(0x00018000, 0x00017ffe): ("RGBA", "LA"),# photo YCC(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),(0x00028000, 0x00028001, 0x00028002, 0x00027ffe): ("RGBA", "YCCA;P"),# standard RGB (NIFRGB)(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),(0x00038000, 0x00038001, 0x00038002, 0x00037ffe): ("RGBA", "RGBA"),}## --------------------------------------------------------------------def _accept(prefix):return prefix[:8] == olefile.MAGIC### Image plugin for the FlashPix images.class FpxImageFile(ImageFile.ImageFile):format = "FPX"format_description = "FlashPix"def _open(self):## read the OLE directory and see if this is a likely# to be a FlashPix filetry:self.ole = olefile.OleFileIO(self.fp)except IOError:raise SyntaxError("not an FPX file; invalid OLE file")if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":raise SyntaxError("not an FPX file; bad root CLSID")self._open_index(1)def _open_index(self, index=1):## get the Image Contents Property Setprop = self.ole.getproperties(["Data Object Store %06d" % index,"\005Image Contents"])# size (highest resolution)self.size = prop[0x1000002], prop[0x1000003]size = max(self.size)i = 1while size > 64:size = size / 2i += 1self.maxid = i - 1# mode. instead of using a single field for this, flashpix# requires you to specify the mode for each channel in each# resolution subimage, and leaves it to the decoder to make# sure that they all match. for now, we'll cheat and assume# that this is always the case.id = self.maxid << 16s = prop[0x2000002 | id]colors = []for i in range(i32(s, 4)):# note: for now, we ignore the "uncalibrated" flagcolors.append(i32(s, 8+i*4) & 0x7fffffff)self.mode, self.rawmode = MODES[tuple(colors)]# load JPEG tables, if anyself.jpeg = {}for i in range(256):id = 0x3000001 | (i << 16)if id in prop:self.jpeg[i] = prop[id]# print(len(self.jpeg), "tables loaded")self._open_subimage(1, self.maxid)def _open_subimage(self, index=1, subimage=0):## setup tile descriptors for a given subimagestream = ["Data Object Store %06d" % index,"Resolution %04d" % subimage,"Subimage 0000 Header"]fp = self.ole.openstream(stream)# skip prefixfp.read(28)# header streams = fp.read(36)size = i32(s, 4), i32(s, 8)# tilecount = i32(s, 12)tilesize = i32(s, 16), i32(s, 20)# channels = i32(s, 24)offset = i32(s, 28)length = i32(s, 32)# print(size, self.mode, self.rawmode)if size != self.size:raise IOError("subimage mismatch")# get tile descriptorsfp.seek(28 + offset)s = fp.read(i32(s, 12) * length)x = y = 0xsize, ysize = sizextile, ytile = tilesizeself.tile = []for i in range(0, len(s), length):compression = i32(s, i+8)if compression == 0:self.tile.append(("raw", (x, y, x+xtile, y+ytile),i32(s, i) + 28, (self.rawmode)))elif compression == 1:# FIXME: the fill decoder is not implementedself.tile.append(("fill", (x, y, x+xtile, y+ytile),i32(s, i) + 28, (self.rawmode, s[12:16])))elif compression == 2:internal_color_conversion = i8(s[14])jpeg_tables = i8(s[15])rawmode = self.rawmodeif internal_color_conversion:# The image is stored as usual (usually YCbCr).if rawmode == "RGBA":# For "RGBA", data is stored as YCbCrA based on# negative RGB. The following trick works around# this problem :jpegmode, rawmode = "YCbCrK", "CMYK"else:jpegmode = None # let the decoder decideelse:# The image is stored as defined by rawmodejpegmode = rawmodeself.tile.append(("jpeg", (x, y, x+xtile, y+ytile),i32(s, i) + 28, (rawmode, jpegmode)))# FIXME: jpeg tables are tile dependent; the prefix# data must be placed in the tile descriptor itself!if jpeg_tables:self.tile_prefix = self.jpeg[jpeg_tables]else:raise IOError("unknown/invalid compression")x = x + xtileif x >= xsize:x, y = 0, y + ytileif y >= ysize:break # isn't really requiredself.stream = streamself.fp = Nonedef load(self):if not self.fp:self.fp = self.ole.openstream(self.stream[:2] +["Subimage 0000 Data"])return ImageFile.ImageFile.load(self)## --------------------------------------------------------------------Image.register_open(FpxImageFile.format, FpxImageFile, _accept)Image.register_extension(FpxImageFile.format, ".fpx")
123version https://git-lfs.github.com/spec/v1oid sha256:940918870726244c0ca1541992bba5ef3a38e50b035e89be4306684915c81d14size 326812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""A Pillow loader for .ftc and .ftu files (FTEX)Jerome Leclanche <jerome@leclan.ch>The contents of this file are hereby released in the public domain (CC0)Full text of the CC0 license:https://creativecommons.org/publicdomain/zero/1.0/Independence War 2: Edge Of Chaos - Texture File Format - 16 October 2001The textures used for 3D objects in Independence War 2: Edge Of Chaos are in apacked custom format called FTEX. This file format uses file extensions FTC and FTU.* FTC files are compressed textures (using standard texture compression).* FTU files are not compressed.Texture File FormatThe FTC and FTU texture files both use the same format. Thishas the following structure:{header}{format_directory}{data}Where:{header} = { u32:magic, u32:version, u32:width, u32:height, u32:mipmap_count, u32:format_count }* The "magic" number is "FTEX".* "width" and "height" are the dimensions of the texture.* "mipmap_count" is the number of mipmaps in the texture.* "format_count" is the number of texture formats (different versions of the same texture) in this file.{format_directory} = format_count * { u32:format, u32:where }The format value is 0 for DXT1 compressed textures and 1 for 24-bit RGB uncompressed textures.The texture data for a format starts at the position "where" in the file.Each set of texture data in the file has the following structure:{data} = format_count * { u32:mipmap_size, mipmap_size * { u8 } }* "mipmap_size" is the number of bytes in that mip level. For compressed textures this is thesize of the texture data compressed with DXT1. For 24 bit uncompressed textures, this is 3 * width * height.Following this are the image bytes for that mipmap level.Note: All data is stored in little-Endian (Intel) byte order."""import structfrom io import BytesIOfrom . import Image, ImageFileMAGIC = b"FTEX"FORMAT_DXT1 = 0FORMAT_UNCOMPRESSED = 1class FtexImageFile(ImageFile.ImageFile):format = "FTEX"format_description = "Texture File Format (IW2:EOC)"def _open(self):magic = struct.unpack("<I", self.fp.read(4))version = struct.unpack("<i", self.fp.read(4))self.size = struct.unpack("<2i", self.fp.read(8))mipmap_count, format_count = struct.unpack("<2i", self.fp.read(8))self.mode = "RGB"# Only support single-format files. I don't know of any multi-format file.assert format_count == 1format, where = struct.unpack("<2i", self.fp.read(8))self.fp.seek(where)mipmap_size, = struct.unpack("<i", self.fp.read(4))data = self.fp.read(mipmap_size)if format == FORMAT_DXT1:self.mode = "RGBA"self.tile = [("bcn", (0, 0) + self.size, 0, (1))]elif format == FORMAT_UNCOMPRESSED:self.tile = [("raw", (0, 0) + self.size, 0, ('RGB', 0, 1))]else:raise ValueError("Invalid texture compression format: %r" % (format))self.fp.close()self.fp = BytesIO(data)def load_seek(self, pos):passdef _validate(prefix):return prefix[:4] == MAGICImage.register_open(FtexImageFile.format, FtexImageFile, _validate)Image.register_extensions(FtexImageFile.format, [".ftc", ".ftu"])
123version https://git-lfs.github.com/spec/v1oid sha256:733b70ddc3dda448f39509d68fc9a70b6ad9c544781bae6fd99797846735ec91size 272312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394## The Python Imaging Library## load a GIMP brush file## History:# 96-03-14 fl Created# 16-01-08 es Version 2## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996.# Copyright (c) Eric Soroos 2016.## See the README file for information on usage and redistribution.### See https://github.com/GNOME/gimp/blob/master/devel-docs/gbr.txt for# format documentation.## This code Interprets version 1 and 2 .gbr files.# Version 1 files are obsolete, and should not be used for new# brushes.# Version 2 files are saved by GIMP v2.8 (at least)# Version 3 files have a format specifier of 18 for 16bit floats in# the color depth field. This is currently unsupported by Pillow.from . import Image, ImageFilefrom ._binary import i32be as i32def _accept(prefix):return len(prefix) >= 8 and i32(prefix[:4]) >= 20 and i32(prefix[4:8]) in (1, 2)### Image plugin for the GIMP brush format.class GbrImageFile(ImageFile.ImageFile):format = "GBR"format_description = "GIMP brush file"def _open(self):header_size = i32(self.fp.read(4))version = i32(self.fp.read(4))if header_size < 20:raise SyntaxError("not a GIMP brush")if version not in (1, 2):raise SyntaxError("Unsupported GIMP brush version: %s" % version)width = i32(self.fp.read(4))height = i32(self.fp.read(4))color_depth = i32(self.fp.read(4))if width <= 0 or height <= 0:raise SyntaxError("not a GIMP brush")if color_depth not in (1, 4):raise SyntaxError("Unsupported GIMP brush color depth: %s" % color_depth)if version == 1:comment_length = header_size-20else:comment_length = header_size-28magic_number = self.fp.read(4)if magic_number != b'GIMP':raise SyntaxError("not a GIMP brush, bad magic number")self.info['spacing'] = i32(self.fp.read(4))comment = self.fp.read(comment_length)[:-1]if color_depth == 1:self.mode = "L"else:self.mode = 'RGBA'self.size = width, heightself.info["comment"] = comment# Image might not be smallImage._decompression_bomb_check(self.size)# Data is an uncompressed block of w * h * bytes/pixelself._data_size = width * height * color_depthdef load(self):self.im = Image.core.new(self.mode, self.size)self.frombytes(self.fp.read(self._data_size))## registryImage.register_open(GbrImageFile.format, GbrImageFile, _accept)Image.register_extension(GbrImageFile.format, ".gbr")
123version https://git-lfs.github.com/spec/v1oid sha256:de5b0cd5d8727ff525c45a3e111090739150df083544e879a3bbde434262653bsize 22661234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283## The Python Imaging Library.# $Id$## GD file handling## History:# 1996-04-12 fl Created## Copyright (c) 1997 by Secret Labs AB.# Copyright (c) 1996 by Fredrik Lundh.## See the README file for information on usage and redistribution.## NOTE: This format cannot be automatically recognized, so the# class is not registered for use with Image.open(). To open a# gd file, use the GdImageFile.open() function instead.# THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This# implementation is provided for convenience and demonstrational# purposes only.from . import ImageFile, ImagePalettefrom ._binary import i8, i16be as i16, i32be as i32__version__ = "0.1"### Image plugin for the GD uncompressed format. Note that this format# is not supported by the standard <b>Image.open</b> function. To use# this plugin, you have to import the <b>GdImageFile</b> module and# use the <b>GdImageFile.open</b> function.class GdImageFile(ImageFile.ImageFile):format = "GD"format_description = "GD uncompressed images"def _open(self):# Headers = self.fp.read(1037)if not i16(s[:2]) in [65534, 65535]:raise SyntaxError("Not a valid GD 2.x .gd file")self.mode = "L" # FIXME: "P"self.size = i16(s[2:4]), i16(s[4:6])trueColor = i8(s[6])trueColorOffset = 2 if trueColor else 0# transparency indextindex = i32(s[7+trueColorOffset:7+trueColorOffset+4])if tindex < 256:self.info["transparency"] = tindexself.palette = ImagePalette.raw("XBGR", s[7+trueColorOffset+4:7+trueColorOffset+4+256*4])self.tile = [("raw", (0, 0)+self.size, 7+trueColorOffset+4+256*4, ("L", 0, 1))]def open(fp, mode="r"):"""Load texture from a GD image file.:param filename: GD file name, or an opened file handle.:param mode: Optional mode. In this version, if the mode argumentis given, it must be "r".:returns: An image instance.:raises IOError: If the image could not be read."""if mode != "r":raise ValueError("bad mode")try:return GdImageFile(fp)except SyntaxError:raise IOError("cannot identify this image file")
123version https://git-lfs.github.com/spec/v1oid sha256:c78a56c2834466830a5352c65282696c6096e0c51280f7e63ce78073c5234eddsize 26714123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814## The Python Imaging Library.# $Id$## GIF file handling## History:# 1995-09-01 fl Created# 1996-12-14 fl Added interlace support# 1996-12-30 fl Added animation support# 1997-01-05 fl Added write support, fixed local colour map bug# 1997-02-23 fl Make sure to load raster data in getdata()# 1997-07-05 fl Support external decoder (0.4)# 1998-07-09 fl Handle all modes when saving (0.5)# 1998-07-15 fl Renamed offset attribute to avoid name clash# 2001-04-16 fl Added rewind support (seek to frame 0) (0.6)# 2001-04-17 fl Added palette optimization (0.7)# 2002-06-06 fl Added transparency support for save (0.8)# 2004-02-24 fl Disable interlacing for small images## Copyright (c) 1997-2004 by Secret Labs AB# Copyright (c) 1995-2004 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFile, ImagePalette, ImageChops, ImageSequencefrom ._binary import i8, i16le as i16, o8, o16le as o16import itertools__version__ = "0.9"# --------------------------------------------------------------------# Identify/read GIF filesdef _accept(prefix):return prefix[:6] in [b"GIF87a", b"GIF89a"]### Image plugin for GIF images. This plugin supports both GIF87 and# GIF89 images.class GifImageFile(ImageFile.ImageFile):format = "GIF"format_description = "Compuserve GIF"_close_exclusive_fp_after_loading = Falseglobal_palette = Nonedef data(self):s = self.fp.read(1)if s and i8(s):return self.fp.read(i8(s))return Nonedef _open(self):# Screens = self.fp.read(13)if s[:6] not in [b"GIF87a", b"GIF89a"]:raise SyntaxError("not a GIF file")self.info["version"] = s[:6]self.size = i16(s[6:]), i16(s[8:])self.tile = []flags = i8(s[10])bits = (flags & 7) + 1if flags & 128:# get global paletteself.info["background"] = i8(s[11])# check if palette contains colour indicesp = self.fp.read(3 << bits)for i in range(0, len(p), 3):if not (i//3 == i8(p[i]) == i8(p[i+1]) == i8(p[i+2])):p = ImagePalette.raw("RGB", p)self.global_palette = self.palette = pbreakself.__fp = self.fp # FIXME: hackself.__rewind = self.fp.tell()self._n_frames = Noneself._is_animated = Noneself._seek(0) # get ready to read first frame@propertydef n_frames(self):if self._n_frames is None:current = self.tell()try:while True:self.seek(self.tell() + 1)except EOFError:self._n_frames = self.tell() + 1self.seek(current)return self._n_frames@propertydef is_animated(self):if self._is_animated is None:if self._n_frames is not None:self._is_animated = self._n_frames != 1else:current = self.tell()try:self.seek(1)self._is_animated = Trueexcept EOFError:self._is_animated = Falseself.seek(current)return self._is_animateddef seek(self, frame):if not self._seek_check(frame):returnif frame < self.__frame:self._seek(0)last_frame = self.__framefor f in range(self.__frame + 1, frame + 1):try:self._seek(f)except EOFError:self.seek(last_frame)raise EOFError("no more images in GIF file")def _seek(self, frame):if frame == 0:# rewindself.__offset = 0self.dispose = Noneself.dispose_extent = [0, 0, 0, 0] # x0, y0, x1, y1self.__frame = -1self.__fp.seek(self.__rewind)self._prev_im = Noneself.disposal_method = 0else:# ensure that the previous frame was loadedif not self.im:self.load()if frame != self.__frame + 1:raise ValueError("cannot seek to frame %d" % frame)self.__frame = frameself.tile = []self.fp = self.__fpif self.__offset:# backup to last frameself.fp.seek(self.__offset)while self.data():passself.__offset = 0if self.dispose:self.im.paste(self.dispose, self.dispose_extent)from copy import copyself.palette = copy(self.global_palette)while True:s = self.fp.read(1)if not s or s == b";":breakelif s == b"!":## extensions#s = self.fp.read(1)block = self.data()if i8(s) == 249:## graphic control extension#flags = i8(block[0])if flags & 1:self.info["transparency"] = i8(block[3])self.info["duration"] = i16(block[1:3]) * 10# disposal method - find the value of bits 4 - 6dispose_bits = 0b00011100 & flagsdispose_bits = dispose_bits >> 2if dispose_bits:# only set the dispose if it is not# unspecified. I'm not sure if this is# correct, but it seems to prevent the last# frame from looking odd for some animationsself.disposal_method = dispose_bitselif i8(s) == 254:## comment extension#self.info["comment"] = blockelif i8(s) == 255:## application extension#self.info["extension"] = block, self.fp.tell()if block[:11] == b"NETSCAPE2.0":block = self.data()if len(block) >= 3 and i8(block[0]) == 1:self.info["loop"] = i16(block[1:3])while self.data():passelif s == b",":## local image#s = self.fp.read(9)# extentx0, y0 = i16(s[0:]), i16(s[2:])x1, y1 = x0 + i16(s[4:]), y0 + i16(s[6:])self.dispose_extent = x0, y0, x1, y1flags = i8(s[8])interlace = (flags & 64) != 0if flags & 128:bits = (flags & 7) + 1self.palette =\ImagePalette.raw("RGB", self.fp.read(3 << bits))# image databits = i8(self.fp.read(1))self.__offset = self.fp.tell()self.tile = [("gif",(x0, y0, x1, y1),self.__offset,(bits, interlace))]breakelse:pass# raise IOError, "illegal GIF tag `%x`" % i8(s)try:if self.disposal_method < 2:# do not dispose or none specifiedself.dispose = Noneelif self.disposal_method == 2:# replace with background colourself.dispose = Image.core.fill("P", self.size,self.info["background"])else:# replace with previous contentsif self.im:self.dispose = self.im.copy()# only dispose the extent in this frameif self.dispose:self.dispose = self._crop(self.dispose, self.dispose_extent)except (AttributeError, KeyError):passif not self.tile:# self.__fp = Noneraise EOFErrorself.mode = "L"if self.palette:self.mode = "P"def tell(self):return self.__framedef load_end(self):ImageFile.ImageFile.load_end(self)# if the disposal method is 'do not dispose', transparent# pixels should show the content of the previous frameif self._prev_im and self.disposal_method == 1:# we do this by pasting the updated area onto the previous# frame which we then use as the current image contentupdated = self._crop(self.im, self.dispose_extent)self._prev_im.paste(updated, self.dispose_extent,updated.convert('RGBA'))self.im = self._prev_imself._prev_im = self.im.copy()# --------------------------------------------------------------------# Write GIF filesRAWMODE = {"1": "L","L": "L","P": "P"}def _normalize_mode(im, initial_call=False):"""Takes an image (or frame), returns an image in a mode that is appropriatefor saving in a Gif.It may return the original image, or it may return an image converted topalette or 'L' mode.UNDONE: What is the point of mucking with the initial call palette, foran image that shouldn't have a palette, or it would be a mode 'P' andget returned in the RAWMODE clause.:param im: Image object:param initial_call: Default false, set to true for a single frame.:returns: Image object"""if im.mode in RAWMODE:im.load()return imif Image.getmodebase(im.mode) == "RGB":if initial_call:palette_size = 256if im.palette:palette_size = len(im.palette.getdata()[1]) // 3return im.convert("P", palette=Image.ADAPTIVE, colors=palette_size)else:return im.convert("P")return im.convert("L")def _normalize_palette(im, palette, info):"""Normalizes the palette for image.- Sets the palette to the incoming palette, if provided.- Ensures that there's a palette for L mode images- Optimizes the palette if necessary/desired.:param im: Image object:param palette: bytes object containing the source palette, or ....:param info: encoderinfo:returns: Image object"""source_palette = Noneif palette:# a bytes paletteif isinstance(palette, (bytes, bytearray, list)):source_palette = bytearray(palette[:768])if isinstance(palette, ImagePalette.ImagePalette):source_palette = bytearray(itertools.chain.from_iterable(zip(palette.palette[:256],palette.palette[256:512],palette.palette[512:768])))if im.mode == "P":if not source_palette:source_palette = im.im.getpalette("RGB")[:768]else: # L-modeif not source_palette:source_palette = bytearray(i//3 for i in range(768))im.palette = ImagePalette.ImagePalette("RGB",palette=source_palette)used_palette_colors = _get_optimize(im, info)if used_palette_colors is not None:return im.remap_palette(used_palette_colors, source_palette)im.palette.palette = source_palettereturn imdef _write_single_frame(im, fp, palette):im_out = _normalize_mode(im, True)im_out = _normalize_palette(im_out, palette, im.encoderinfo)for s in _get_global_header(im_out, im.encoderinfo):fp.write(s)# local image headerflags = 0if get_interlace(im):flags = flags | 64_write_local_header(fp, im, (0, 0), flags)im_out.encoderconfig = (8, get_interlace(im))ImageFile._save(im_out, fp, [("gif", (0, 0)+im.size, 0,RAWMODE[im_out.mode])])fp.write(b"\0") # end of image datadef _write_multiple_frames(im, fp, palette):duration = im.encoderinfo.get("duration", None)disposal = im.encoderinfo.get('disposal', None)im_frames = []frame_count = 0for imSequence in itertools.chain([im], im.encoderinfo.get("append_images", [])):for im_frame in ImageSequence.Iterator(imSequence):# a copy is required here since seek can still mutate the imageim_frame = _normalize_mode(im_frame.copy())im_frame = _normalize_palette(im_frame, palette, im.encoderinfo)encoderinfo = im.encoderinfo.copy()if isinstance(duration, (list, tuple)):encoderinfo['duration'] = duration[frame_count]if isinstance(disposal, (list, tuple)):encoderinfo["disposal"] = disposal[frame_count]frame_count += 1if im_frames:# delta frameprevious = im_frames[-1]if _get_palette_bytes(im_frame) == _get_palette_bytes(previous['im']):delta = ImageChops.subtract_modulo(im_frame,previous['im'])else:delta = ImageChops.subtract_modulo(im_frame.convert('RGB'),previous['im'].convert('RGB'))bbox = delta.getbbox()if not bbox:# This frame is identical to the previous frameif duration:previous['encoderinfo']['duration'] += encoderinfo['duration']continueelse:bbox = Noneim_frames.append({'im': im_frame,'bbox': bbox,'encoderinfo': encoderinfo})if len(im_frames) > 1:for frame_data in im_frames:im_frame = frame_data['im']if not frame_data['bbox']:# global headerfor s in _get_global_header(im_frame,frame_data['encoderinfo']):fp.write(s)offset = (0, 0)else:# compress differenceframe_data['encoderinfo']['include_color_table'] = Trueim_frame = im_frame.crop(frame_data['bbox'])offset = frame_data['bbox'][:2]_write_frame_data(fp, im_frame, offset, frame_data['encoderinfo'])return Truedef _save_all(im, fp, filename):_save(im, fp, filename, save_all=True)def _save(im, fp, filename, save_all=False):for k, v in im.info.items():im.encoderinfo.setdefault(k, v)# headertry:palette = im.encoderinfo["palette"]except KeyError:palette = Noneim.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True)if not save_all or not _write_multiple_frames(im, fp, palette):_write_single_frame(im, fp, palette)fp.write(b";") # end of fileif hasattr(fp, "flush"):fp.flush()def get_interlace(im):interlace = im.encoderinfo.get("interlace", 1)# workaround for @PIL153if min(im.size) < 16:interlace = 0return interlacedef _write_local_header(fp, im, offset, flags):transparent_color_exists = Falsetry:transparency = im.encoderinfo["transparency"]except KeyError:passelse:transparency = int(transparency)# optimize the block away if transparent color is not usedtransparent_color_exists = Trueused_palette_colors = _get_optimize(im, im.encoderinfo)if used_palette_colors is not None:# adjust the transparency index after optimizetry:transparency = used_palette_colors.index(transparency)except ValueError:transparent_color_exists = Falseif "duration" in im.encoderinfo:duration = int(im.encoderinfo["duration"] / 10)else:duration = 0disposal = int(im.encoderinfo.get('disposal', 0))if transparent_color_exists or duration != 0 or disposal:packed_flag = 1 if transparent_color_exists else 0packed_flag |= disposal << 2if not transparent_color_exists:transparency = 0fp.write(b"!" +o8(249) + # extension introo8(4) + # lengtho8(packed_flag) + # packed fieldso16(duration) + # durationo8(transparency) + # transparency indexo8(0))if "comment" in im.encoderinfo and 1 <= len(im.encoderinfo["comment"]) <= 255:fp.write(b"!" +o8(254) + # extension introo8(len(im.encoderinfo["comment"])) +im.encoderinfo["comment"] +o8(0))if "loop" in im.encoderinfo:number_of_loops = im.encoderinfo["loop"]fp.write(b"!" +o8(255) + # extension introo8(11) +b"NETSCAPE2.0" +o8(3) +o8(1) +o16(number_of_loops) + # number of loopso8(0))include_color_table = im.encoderinfo.get('include_color_table')if include_color_table:palette = im.encoderinfo.get("palette", None)palette_bytes = _get_palette_bytes(im)color_table_size = _get_color_table_size(palette_bytes)if color_table_size:flags = flags | 128 # local color table flagflags = flags | color_table_sizefp.write(b"," +o16(offset[0]) + # offseto16(offset[1]) +o16(im.size[0]) + # sizeo16(im.size[1]) +o8(flags)) # flagsif include_color_table and color_table_size:fp.write(_get_header_palette(palette_bytes))fp.write(o8(8)) # bitsdef _save_netpbm(im, fp, filename):# Unused by default.# To use, uncomment the register_save call at the end of the file.## If you need real GIF compression and/or RGB quantization, you# can use the external NETPBM/PBMPLUS utilities. See comments# below for information on how to enable this.import osfrom subprocess import Popen, check_call, PIPE, CalledProcessErrorfile = im._dump()with open(filename, 'wb') as f:if im.mode != "RGB":with open(os.devnull, 'wb') as devnull:check_call(["ppmtogif", file], stdout=f, stderr=devnull)else:# Pipe ppmquant output into ppmtogif# "ppmquant 256 %s | ppmtogif > %s" % (file, filename)quant_cmd = ["ppmquant", "256", file]togif_cmd = ["ppmtogif"]with open(os.devnull, 'wb') as devnull:quant_proc = Popen(quant_cmd, stdout=PIPE, stderr=devnull)togif_proc = Popen(togif_cmd, stdin=quant_proc.stdout,stdout=f, stderr=devnull)# Allow ppmquant to receive SIGPIPE if ppmtogif exitsquant_proc.stdout.close()retcode = quant_proc.wait()if retcode:raise CalledProcessError(retcode, quant_cmd)retcode = togif_proc.wait()if retcode:raise CalledProcessError(retcode, togif_cmd)try:os.unlink(file)except OSError:pass# Force optimization so that we can test performance against# cases where it took lots of memory and time previously._FORCE_OPTIMIZE = Falsedef _get_optimize(im, info):"""Palette optimization is a potentially expensive operation.This function determines if the palette should be optimized usingsome heuristics, then returns the list of palette entries in use.:param im: Image object:param info: encoderinfo:returns: list of indexes of palette entries in use, or None"""if im.mode in ("P", "L") and info and info.get("optimize", 0):# Potentially expensive operation.# The palette saves 3 bytes per color not used, but palette# lengths are restricted to 3*(2**N) bytes. Max saving would# be 768 -> 6 bytes if we went all the way down to 2 colors.# * If we're over 128 colors, we can't save any space.# * If there aren't any holes, it's not worth collapsing.# * If we have a 'large' image, the palette is in the noise.# create the new palette if not every color is usedoptimise = _FORCE_OPTIMIZE or im.mode == 'L'if optimise or im.width * im.height < 512 * 512:# check which colors are usedused_palette_colors = []for i, count in enumerate(im.histogram()):if count:used_palette_colors.append(i)if optimise or (len(used_palette_colors) <= 128 andmax(used_palette_colors) > len(used_palette_colors)):return used_palette_colorsdef _get_color_table_size(palette_bytes):# calculate the palette size for the headerimport mathcolor_table_size = int(math.ceil(math.log(len(palette_bytes)//3, 2)))-1if color_table_size < 0:color_table_size = 0return color_table_sizedef _get_header_palette(palette_bytes):"""Returns the palette, null padded to the next power of 2 (*3) bytessuitable for direct inclusion in the GIF header:param palette_bytes: Unpadded palette bytes, in RGBRGB form:returns: Null padded palette"""color_table_size = _get_color_table_size(palette_bytes)# add the missing amount of bytes# the palette has to be 2<<n in sizeactual_target_size_diff = (2 << color_table_size) - len(palette_bytes)//3if actual_target_size_diff > 0:palette_bytes += o8(0) * 3 * actual_target_size_diffreturn palette_bytesdef _get_palette_bytes(im):"""Gets the palette for inclusion in the gif header:param im: Image object:returns: Bytes, len<=768 suitable for inclusion in gif header"""return im.palette.palettedef _get_global_header(im, info):"""Return a list of strings representing a GIF header"""# Header Block# http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.aspversion = b"87a"for extensionKey in ["transparency", "duration", "loop", "comment"]:if info and extensionKey in info:if ((extensionKey == "duration" and info[extensionKey] == 0) or(extensionKey == "comment" and not (1 <= len(info[extensionKey]) <= 255))):continueversion = b"89a"breakelse:if im.info.get("version") == b"89a":version = b"89a"palette_bytes = _get_palette_bytes(im)color_table_size = _get_color_table_size(palette_bytes)background = info["background"] if "background" in info else 0return [b"GIF"+version + # signature + versiono16(im.size[0]) + # canvas widtho16(im.size[1]), # canvas height# Logical Screen Descriptor# size of global color table + global color table flago8(color_table_size + 128), # packed fields# background + reserved/aspecto8(background) + o8(0),# Global Color Table_get_header_palette(palette_bytes)]def _write_frame_data(fp, im_frame, offset, params):try:im_frame.encoderinfo = params# local image header_write_local_header(fp, im_frame, offset, 0)ImageFile._save(im_frame, fp, [("gif", (0, 0)+im_frame.size, 0,RAWMODE[im_frame.mode])])fp.write(b"\0") # end of image datafinally:del im_frame.encoderinfo# --------------------------------------------------------------------# Legacy GIF utilitiesdef getheader(im, palette=None, info=None):"""Legacy Method to get Gif data from image.Warning:: May modify image data.:param im: Image object:param palette: bytes object containing the source palette, or ....:param info: encoderinfo:returns: tuple of(list of header items, optimized palette)"""used_palette_colors = _get_optimize(im, info)if info is None:info = {}if "background" not in info and "background" in im.info:info["background"] = im.info["background"]im_mod = _normalize_palette(im, palette, info)im.palette = im_mod.paletteim.im = im_mod.imheader = _get_global_header(im, info)return header, used_palette_colors# To specify duration, add the time in milliseconds to getdata(),# e.g. getdata(im_frame, duration=1000)def getdata(im, offset=(0, 0), **params):"""Legacy MethodReturn a list of strings representing this image.The first string is a local image header, the rest containsencoded image data.:param im: Image object:param offset: Tuple of (x, y) pixels. Defaults to (0,0):param \\**params: E.g. duration or other encoder info parameters:returns: List of Bytes containing gif encoded frame data"""class Collector(object):data = []def write(self, data):self.data.append(data)im.load() # make sure raster data is availablefp = Collector()_write_frame_data(fp, im, offset, params)return fp.data# --------------------------------------------------------------------# RegistryImage.register_open(GifImageFile.format, GifImageFile, _accept)Image.register_save(GifImageFile.format, _save)Image.register_save_all(GifImageFile.format, _save_all)Image.register_extension(GifImageFile.format, ".gif")Image.register_mime(GifImageFile.format, "image/gif")## Uncomment the following line if you wish to use NETPBM/PBMPLUS# instead of the built-in "uncompressed" GIF encoder# Image.register_save(GifImageFile.format, _save_netpbm)
123version https://git-lfs.github.com/spec/v1oid sha256:cecefebc701d542227450443c762b97c1a687cc9514741912b119599c50631a8size 3345123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138## Python Imaging Library# $Id$## stuff to read (and render) GIMP gradient files## History:# 97-08-23 fl Created## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1997.## See the README file for information on usage and redistribution.#from math import pi, log, sin, sqrtfrom ._binary import o8# --------------------------------------------------------------------# Stuff to translate curve segments to palette values (derived from# the corresponding code in GIMP, written by Federico Mena Quintero.# See the GIMP distribution for more information.)#EPSILON = 1e-10def linear(middle, pos):if pos <= middle:if middle < EPSILON:return 0.0else:return 0.5 * pos / middleelse:pos = pos - middlemiddle = 1.0 - middleif middle < EPSILON:return 1.0else:return 0.5 + 0.5 * pos / middledef curved(middle, pos):return pos ** (log(0.5) / log(max(middle, EPSILON)))def sine(middle, pos):return (sin((-pi / 2.0) + pi * linear(middle, pos)) + 1.0) / 2.0def sphere_increasing(middle, pos):return sqrt(1.0 - (linear(middle, pos) - 1.0) ** 2)def sphere_decreasing(middle, pos):return 1.0 - sqrt(1.0 - linear(middle, pos) ** 2)SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]class GradientFile(object):gradient = Nonedef getpalette(self, entries=256):palette = []ix = 0x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]for i in range(entries):x = i / float(entries-1)while x1 < x:ix += 1x0, x1, xm, rgb0, rgb1, segment = self.gradient[ix]w = x1 - x0if w < EPSILON:scale = segment(0.5, 0.5)else:scale = segment((xm - x0) / w, (x - x0) / w)# expand to RGBAr = o8(int(255 * ((rgb1[0] - rgb0[0]) * scale + rgb0[0]) + 0.5))g = o8(int(255 * ((rgb1[1] - rgb0[1]) * scale + rgb0[1]) + 0.5))b = o8(int(255 * ((rgb1[2] - rgb0[2]) * scale + rgb0[2]) + 0.5))a = o8(int(255 * ((rgb1[3] - rgb0[3]) * scale + rgb0[3]) + 0.5))# add to palettepalette.append(r + g + b + a)return b"".join(palette), "RGBA"### File handler for GIMP's gradient format.class GimpGradientFile(GradientFile):def __init__(self, fp):if fp.readline()[:13] != b"GIMP Gradient":raise SyntaxError("not a GIMP gradient file")line = fp.readline()# GIMP 1.2 gradient files don't contain a name, but GIMP 1.3 files doif line.startswith(b"Name: "):line = fp.readline().strip()count = int(line)gradient = []for i in range(count):s = fp.readline().split()w = [float(x) for x in s[:11]]x0, x1 = w[0], w[2]xm = w[1]rgb0 = w[3:7]rgb1 = w[7:11]segment = SEGMENTS[int(s[11])]cspace = int(s[12])if cspace != 0:raise IOError("cannot handle HSV colour space")gradient.append((x0, x1, xm, rgb0, rgb1, segment))self.gradient = gradient
123version https://git-lfs.github.com/spec/v1oid sha256:d68ddbdd684f09e507cfff6e59fa2b2b4890fce05e1a814c1e712c9fd95f0a33size 13391234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162## Python Imaging Library# $Id$## stuff to read GIMP palette files## History:# 1997-08-23 fl Created# 2004-09-07 fl Support GIMP 2.0 palette files.## Copyright (c) Secret Labs AB 1997-2004. All rights reserved.# Copyright (c) Fredrik Lundh 1997-2004.## See the README file for information on usage and redistribution.#import refrom ._binary import o8### File handler for GIMP's palette format.class GimpPaletteFile(object):rawmode = "RGB"def __init__(self, fp):self.palette = [o8(i)*3 for i in range(256)]if fp.readline()[:12] != b"GIMP Palette":raise SyntaxError("not a GIMP palette file")i = 0while i <= 255:s = fp.readline()if not s:break# skip fields and comment linesif re.match(br"\w+:|#", s):continueif len(s) > 100:raise SyntaxError("bad palette file")v = tuple(map(int, s.split()[:3]))if len(v) != 3:raise ValueError("bad palette entry")if 0 <= i <= 255:self.palette[i] = o8(v[0]) + o8(v[1]) + o8(v[2])i += 1self.palette = b"".join(self.palette)def getpalette(self):return self.palette, self.rawmode
123version https://git-lfs.github.com/spec/v1oid sha256:636a7f5bc3d3bf1dce0a7a6c383ef534971ea09b569a05b2fda70eb79c125771size 154112345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273## The Python Imaging Library# $Id$## GRIB stub adapter## Copyright (c) 1996-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFilefrom ._binary import i8_handler = Nonedef register_handler(handler):"""Install application-specific GRIB image handler.:param handler: Handler object."""global _handler_handler = handler# --------------------------------------------------------------------# Image adapterdef _accept(prefix):return prefix[0:4] == b"GRIB" and i8(prefix[7]) == 1class GribStubImageFile(ImageFile.StubImageFile):format = "GRIB"format_description = "GRIB"def _open(self):offset = self.fp.tell()if not _accept(self.fp.read(8)):raise SyntaxError("Not a GRIB file")self.fp.seek(offset)# make something upself.mode = "F"self.size = 1, 1loader = self._load()if loader:loader.open(self)def _load(self):return _handlerdef _save(im, fp, filename):if _handler is None or not hasattr("_handler", "save"):raise IOError("GRIB save handler not installed")_handler.save(im, fp, filename)# --------------------------------------------------------------------# RegistryImage.register_open(GribStubImageFile.format, GribStubImageFile, _accept)Image.register_save(GribStubImageFile.format, _save)Image.register_extension(GribStubImageFile.format, ".grib")
123version https://git-lfs.github.com/spec/v1oid sha256:d6769cad3a4ed2d3736d5bde93476fc516c09a59f18bc9fe27a81db3e58e0c4asize 1515123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172## The Python Imaging Library# $Id$## HDF5 stub adapter## Copyright (c) 2000-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageFile_handler = Nonedef register_handler(handler):"""Install application-specific HDF5 image handler.:param handler: Handler object."""global _handler_handler = handler# --------------------------------------------------------------------# Image adapterdef _accept(prefix):return prefix[:8] == b"\x89HDF\r\n\x1a\n"class HDF5StubImageFile(ImageFile.StubImageFile):format = "HDF5"format_description = "HDF5"def _open(self):offset = self.fp.tell()if not _accept(self.fp.read(8)):raise SyntaxError("Not an HDF file")self.fp.seek(offset)# make something upself.mode = "F"self.size = 1, 1loader = self._load()if loader:loader.open(self)def _load(self):return _handlerdef _save(im, fp, filename):if _handler is None or not hasattr("_handler", "save"):raise IOError("HDF5 save handler not installed")_handler.save(im, fp, filename)# --------------------------------------------------------------------# RegistryImage.register_open(HDF5StubImageFile.format, HDF5StubImageFile, _accept)Image.register_save(HDF5StubImageFile.format, _save)Image.register_extensions(HDF5StubImageFile.format, [".h5", ".hdf"])
123version https://git-lfs.github.com/spec/v1oid sha256:0df4aad78791c91f772648f58f849f7e36f7d70c6757d413ca1bccdfe7074a0fsize 10980123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374## The Python Imaging Library.# $Id$## macOS icns file decoder, based on icns.py by Bob Ippolito.## history:# 2004-10-09 fl Turned into a PIL plugin; removed 2.3 dependencies.## Copyright (c) 2004 by Bob Ippolito.# Copyright (c) 2004 by Secret Labs.# Copyright (c) 2004 by Fredrik Lundh.# Copyright (c) 2014 by Alastair Houghton.## See the README file for information on usage and redistribution.#from PIL import Image, ImageFile, PngImagePluginfrom PIL._binary import i8import ioimport osimport shutilimport structimport sysimport tempfileenable_jpeg2k = hasattr(Image.core, 'jp2klib_version')if enable_jpeg2k:from PIL import Jpeg2KImagePluginHEADERSIZE = 8def nextheader(fobj):return struct.unpack('>4sI', fobj.read(HEADERSIZE))def read_32t(fobj, start_length, size):# The 128x128 icon seems to have an extra header for some reason.(start, length) = start_lengthfobj.seek(start)sig = fobj.read(4)if sig != b'\x00\x00\x00\x00':raise SyntaxError('Unknown signature, expecting 0x00000000')return read_32(fobj, (start + 4, length - 4), size)def read_32(fobj, start_length, size):"""Read a 32bit RGB icon resource. Seems to be either uncompressed oran RLE packbits-like scheme."""(start, length) = start_lengthfobj.seek(start)pixel_size = (size[0] * size[2], size[1] * size[2])sizesq = pixel_size[0] * pixel_size[1]if length == sizesq * 3:# uncompressed ("RGBRGBGB")indata = fobj.read(length)im = Image.frombuffer("RGB", pixel_size, indata, "raw", "RGB", 0, 1)else:# decode imageim = Image.new("RGB", pixel_size, None)for band_ix in range(3):data = []bytesleft = sizesqwhile bytesleft > 0:byte = fobj.read(1)if not byte:breakbyte = i8(byte)if byte & 0x80:blocksize = byte - 125byte = fobj.read(1)for i in range(blocksize):data.append(byte)else:blocksize = byte + 1data.append(fobj.read(blocksize))bytesleft -= blocksizeif bytesleft <= 0:breakif bytesleft != 0:raise SyntaxError("Error reading channel [%r left]" % bytesleft)band = Image.frombuffer("L", pixel_size, b"".join(data), "raw", "L", 0, 1)im.im.putband(band.im, band_ix)return {"RGB": im}def read_mk(fobj, start_length, size):# Alpha masks seem to be uncompressedstart = start_length[0]fobj.seek(start)pixel_size = (size[0] * size[2], size[1] * size[2])sizesq = pixel_size[0] * pixel_size[1]band = Image.frombuffer("L", pixel_size, fobj.read(sizesq), "raw", "L", 0, 1)return {"A": band}def read_png_or_jpeg2000(fobj, start_length, size):(start, length) = start_lengthfobj.seek(start)sig = fobj.read(12)if sig[:8] == b'\x89PNG\x0d\x0a\x1a\x0a':fobj.seek(start)im = PngImagePlugin.PngImageFile(fobj)return {"RGBA": im}elif sig[:4] == b'\xff\x4f\xff\x51' \or sig[:4] == b'\x0d\x0a\x87\x0a' \or sig == b'\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a':if not enable_jpeg2k:raise ValueError('Unsupported icon subimage format (rebuild PIL ''with JPEG 2000 support to fix this)')# j2k, jpc or j2cfobj.seek(start)jp2kstream = fobj.read(length)f = io.BytesIO(jp2kstream)im = Jpeg2KImagePlugin.Jpeg2KImageFile(f)if im.mode != 'RGBA':im = im.convert('RGBA')return {"RGBA": im}else:raise ValueError('Unsupported icon subimage format')class IcnsFile(object):SIZES = {(512, 512, 2): [(b'ic10', read_png_or_jpeg2000),],(512, 512, 1): [(b'ic09', read_png_or_jpeg2000),],(256, 256, 2): [(b'ic14', read_png_or_jpeg2000),],(256, 256, 1): [(b'ic08', read_png_or_jpeg2000),],(128, 128, 2): [(b'ic13', read_png_or_jpeg2000),],(128, 128, 1): [(b'ic07', read_png_or_jpeg2000),(b'it32', read_32t),(b't8mk', read_mk),],(64, 64, 1): [(b'icp6', read_png_or_jpeg2000),],(32, 32, 2): [(b'ic12', read_png_or_jpeg2000),],(48, 48, 1): [(b'ih32', read_32),(b'h8mk', read_mk),],(32, 32, 1): [(b'icp5', read_png_or_jpeg2000),(b'il32', read_32),(b'l8mk', read_mk),],(16, 16, 2): [(b'ic11', read_png_or_jpeg2000),],(16, 16, 1): [(b'icp4', read_png_or_jpeg2000),(b'is32', read_32),(b's8mk', read_mk),],}def __init__(self, fobj):"""fobj is a file-like object as an icns resource"""# signature : (start, length)self.dct = dct = {}self.fobj = fobjsig, filesize = nextheader(fobj)if sig != b'icns':raise SyntaxError('not an icns file')i = HEADERSIZEwhile i < filesize:sig, blocksize = nextheader(fobj)if blocksize <= 0:raise SyntaxError('invalid block header')i += HEADERSIZEblocksize -= HEADERSIZEdct[sig] = (i, blocksize)fobj.seek(blocksize, 1)i += blocksizedef itersizes(self):sizes = []for size, fmts in self.SIZES.items():for (fmt, reader) in fmts:if fmt in self.dct:sizes.append(size)breakreturn sizesdef bestsize(self):sizes = self.itersizes()if not sizes:raise SyntaxError("No 32bit icon resources found")return max(sizes)def dataforsize(self, size):"""Get an icon resource as {channel: array}. Note thatthe arrays are bottom-up like windows bitmaps and will likelyneed to be flipped or transposed in some way."""dct = {}for code, reader in self.SIZES[size]:desc = self.dct.get(code)if desc is not None:dct.update(reader(self.fobj, desc, size))return dctdef getimage(self, size=None):if size is None:size = self.bestsize()if len(size) == 2:size = (size[0], size[1], 1)channels = self.dataforsize(size)im = channels.get('RGBA', None)if im:return imim = channels.get("RGB").copy()try:im.putalpha(channels["A"])except KeyError:passreturn im### Image plugin for Mac OS icons.class IcnsImageFile(ImageFile.ImageFile):"""PIL image support for Mac OS .icns files.Chooses the best resolution, but will possibly loada different size image if you mutate the size attributebefore calling 'load'.The info dictionary has a key 'sizes' that is a listof sizes that the icns file has."""format = "ICNS"format_description = "Mac OS icns resource"def _open(self):self.icns = IcnsFile(self.fp)self.mode = 'RGBA'self.best_size = self.icns.bestsize()self.size = (self.best_size[0] * self.best_size[2],self.best_size[1] * self.best_size[2])self.info['sizes'] = self.icns.itersizes()# Just use this to see if it's loaded or not yet.self.tile = ('',)def load(self):if len(self.size) == 3:self.best_size = self.sizeself.size = (self.best_size[0] * self.best_size[2],self.best_size[1] * self.best_size[2])Image.Image.load(self)if not self.tile:returnself.load_prepare()# This is likely NOT the best way to do it, but whatever.im = self.icns.getimage(self.best_size)# If this is a PNG or JPEG 2000, it won't be loaded yetim.load()self.im = im.imself.mode = im.modeself.size = im.sizeself.fp = Noneself.icns = Noneself.tile = ()self.load_end()def _save(im, fp, filename):"""Saves the image as a series of PNG files,that are then converted to a .icns fileusing the macOS command line utility 'iconutil'.macOS only."""if hasattr(fp, "flush"):fp.flush()# create the temporary set of pngsiconset = tempfile.mkdtemp('.iconset')provided_images = {im.width: imfor im in im.encoderinfo.get("append_images", [])}last_w = Nonefor w in [16, 32, 128, 256, 512]:prefix = 'icon_{}x{}'.format(w, w)first_path = os.path.join(iconset, prefix+'.png')if last_w == w:shutil.copyfile(second_path, first_path)else:im_w = provided_images.get(w, im.resize((w, w), Image.LANCZOS))im_w.save(first_path)second_path = os.path.join(iconset, prefix+'@2x.png')im_w2 = provided_images.get(w*2, im.resize((w*2, w*2), Image.LANCZOS))im_w2.save(second_path)last_w = w*2# iconutil -c icns -o {} {}from subprocess import Popen, PIPE, CalledProcessErrorconvert_cmd = ["iconutil", "-c", "icns", "-o", filename, iconset]with open(os.devnull, 'wb') as devnull:convert_proc = Popen(convert_cmd, stdout=PIPE, stderr=devnull)convert_proc.stdout.close()retcode = convert_proc.wait()# remove the temporary filesshutil.rmtree(iconset)if retcode:raise CalledProcessError(retcode, convert_cmd)Image.register_open(IcnsImageFile.format, IcnsImageFile,lambda x: x[:4] == b'icns')Image.register_extension(IcnsImageFile.format, '.icns')if sys.platform == 'darwin':Image.register_save(IcnsImageFile.format, _save)Image.register_mime(IcnsImageFile.format, "image/icns")if __name__ == '__main__':if len(sys.argv) < 2:print("Syntax: python IcnsImagePlugin.py [file]")sys.exit()imf = IcnsImageFile(open(sys.argv[1], 'rb'))for size in imf.info['sizes']:imf.size = sizeimf.load()im = imf.imim.save('out-%s-%s-%s.png' % size)im = Image.open(sys.argv[1])im.save("out.png")if sys.platform == 'windows':os.startfile("out.png")
123version https://git-lfs.github.com/spec/v1oid sha256:c0d770852de3de58632e8449f42a47c2499e2bdaea266ed35b60328d17776f53size 9331123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284## The Python Imaging Library.# $Id$## Windows Icon support for PIL## History:# 96-05-27 fl Created## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996.## See the README file for information on usage and redistribution.## This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis# <casadebender@gmail.com>.# https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki## Icon format references:# * https://en.wikipedia.org/wiki/ICO_(file_format)# * https://msdn.microsoft.com/en-us/library/ms997538.aspximport structfrom io import BytesIOfrom . import Image, ImageFile, BmpImagePlugin, PngImagePluginfrom ._binary import i8, i16le as i16, i32le as i32from math import log, ceil__version__ = "0.1"## --------------------------------------------------------------------_MAGIC = b"\0\0\1\0"def _save(im, fp, filename):fp.write(_MAGIC) # (2+2)sizes = im.encoderinfo.get("sizes",[(16, 16), (24, 24), (32, 32), (48, 48),(64, 64), (128, 128), (256, 256)])width, height = im.sizesizes = filter(lambda x: False if (x[0] > width or x[1] > height orx[0] > 256 or x[1] > 256) else True,sizes)sizes = list(sizes)fp.write(struct.pack("<H", len(sizes))) # idCount(2)offset = fp.tell() + len(sizes)*16for size in sizes:width, height = size# 0 means 256fp.write(struct.pack("B", width if width < 256 else 0)) # bWidth(1)fp.write(struct.pack("B", height if height < 256 else 0)) # bHeight(1)fp.write(b"\0") # bColorCount(1)fp.write(b"\0") # bReserved(1)fp.write(b"\0\0") # wPlanes(2)fp.write(struct.pack("<H", 32)) # wBitCount(2)image_io = BytesIO()tmp = im.copy()tmp.thumbnail(size, Image.LANCZOS)tmp.save(image_io, "png")image_io.seek(0)image_bytes = image_io.read()bytes_len = len(image_bytes)fp.write(struct.pack("<I", bytes_len)) # dwBytesInRes(4)fp.write(struct.pack("<I", offset)) # dwImageOffset(4)current = fp.tell()fp.seek(offset)fp.write(image_bytes)offset = offset + bytes_lenfp.seek(current)def _accept(prefix):return prefix[:4] == _MAGICclass IcoFile(object):def __init__(self, buf):"""Parse image from file-like object containing ico file data"""# check magics = buf.read(6)if not _accept(s):raise SyntaxError("not an ICO file")self.buf = bufself.entry = []# Number of items in fileself.nb_items = i16(s[4:])# Get headers for each itemfor i in range(self.nb_items):s = buf.read(16)icon_header = {'width': i8(s[0]),'height': i8(s[1]),'nb_color': i8(s[2]), # No. of colors in image (0 if >=8bpp)'reserved': i8(s[3]),'planes': i16(s[4:]),'bpp': i16(s[6:]),'size': i32(s[8:]),'offset': i32(s[12:])}# See Wikipediafor j in ('width', 'height'):if not icon_header[j]:icon_header[j] = 256# See Wikipedia notes about color depth.# We need this just to differ images with equal sizesicon_header['color_depth'] = (icon_header['bpp'] or(icon_header['nb_color'] != 0 andceil(log(icon_header['nb_color'],2))) or 256)icon_header['dim'] = (icon_header['width'], icon_header['height'])icon_header['square'] = (icon_header['width'] *icon_header['height'])self.entry.append(icon_header)self.entry = sorted(self.entry, key=lambda x: x['color_depth'])# ICO images are usually squares# self.entry = sorted(self.entry, key=lambda x: x['width'])self.entry = sorted(self.entry, key=lambda x: x['square'])self.entry.reverse()def sizes(self):"""Get a list of all available icon sizes and color depths."""return {(h['width'], h['height']) for h in self.entry}def getimage(self, size, bpp=False):"""Get an image from the icon"""for (i, h) in enumerate(self.entry):if size == h['dim'] and (bpp is False or bpp == h['color_depth']):return self.frame(i)return self.frame(0)def frame(self, idx):"""Get an image from frame idx"""header = self.entry[idx]self.buf.seek(header['offset'])data = self.buf.read(8)self.buf.seek(header['offset'])if data[:8] == PngImagePlugin._MAGIC:# png frameim = PngImagePlugin.PngImageFile(self.buf)else:# XOR + AND mask bmp frameim = BmpImagePlugin.DibImageFile(self.buf)# change tile dimension to only encompass XOR imageim.size = (im.size[0], int(im.size[1] / 2))d, e, o, a = im.tile[0]im.tile[0] = d, (0, 0) + im.size, o, a# figure out where AND mask image startsmode = a[0]bpp = 8for k, v in BmpImagePlugin.BIT2MODE.items():if mode == v[1]:bpp = kbreakif 32 == bpp:# 32-bit color depth icon image allows semitransparent areas# PIL's DIB format ignores transparency bits, recover them.# The DIB is packed in BGRX byte order where X is the alpha# channel.# Back up to start of bmp dataself.buf.seek(o)# extract every 4th byte (eg. 3,7,11,15,...)alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]# convert to an 8bpp grayscale imagemask = Image.frombuffer('L', # 8bppim.size, # (w, h)alpha_bytes, # source chars'raw', # raw decoder('L', 0, -1) # 8bpp inverted, unpadded, reversed)else:# get AND image from end of bitmapw = im.size[0]if (w % 32) > 0:# bitmap row data is aligned to word boundariesw += 32 - (im.size[0] % 32)# the total mask data is# padded row size * height / bits per charand_mask_offset = o + int(im.size[0] * im.size[1] *(bpp / 8.0))total_bytes = int((w * im.size[1]) / 8)self.buf.seek(and_mask_offset)mask_data = self.buf.read(total_bytes)# convert raw data to imagemask = Image.frombuffer('1', # 1 bppim.size, # (w, h)mask_data, # source chars'raw', # raw decoder('1;I', int(w/8), -1) # 1bpp inverted, padded, reversed)# now we have two images, im is XOR image and mask is AND image# apply mask image as alpha channelim = im.convert('RGBA')im.putalpha(mask)return im### Image plugin for Windows Icon files.class IcoImageFile(ImageFile.ImageFile):"""PIL read-only image support for Microsoft Windows .ico files.By default the largest resolution image in the file will be loaded. Thiscan be changed by altering the 'size' attribute before calling 'load'.The info dictionary has a key 'sizes' that is a list of the sizes availablein the icon file.Handles classic, XP and Vista icon formats.This plugin is a refactored version of Win32IconImagePlugin by Bryan Davis<casadebender@gmail.com>.https://code.google.com/archive/p/casadebender/wikis/Win32IconImagePlugin.wiki"""format = "ICO"format_description = "Windows Icon"def _open(self):self.ico = IcoFile(self.fp)self.info['sizes'] = self.ico.sizes()self.size = self.ico.entry[0]['dim']self.load()def load(self):im = self.ico.getimage(self.size)# if tile is PNG, it won't really be loaded yetim.load()self.im = im.imself.mode = im.modeself.size = im.sizedef load_seek(self):# Flag the ImageFile.Parser so that it# just does all the decode at the end.pass## --------------------------------------------------------------------Image.register_open(IcoImageFile.format, IcoImageFile, _accept)Image.register_save(IcoImageFile.format, _save)Image.register_extension(IcoImageFile.format, ".ico")
123version https://git-lfs.github.com/spec/v1oid sha256:bc88b89c397a21263c3b1edef0a36240cf49688fdcac564472f5fe16a661a4b4size 10162123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347## The Python Imaging Library.# $Id$## IFUNC IM file handling for PIL## history:# 1995-09-01 fl Created.# 1997-01-03 fl Save palette images# 1997-01-08 fl Added sequence support# 1997-01-23 fl Added P and RGB save support# 1997-05-31 fl Read floating point images# 1997-06-22 fl Save floating point images# 1997-08-27 fl Read and save 1-bit images# 1998-06-25 fl Added support for RGB+LUT images# 1998-07-02 fl Added support for YCC images# 1998-07-15 fl Renamed offset attribute to avoid name clash# 1998-12-29 fl Added I;16 support# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)# 2003-09-26 fl Added LA/PA support## Copyright (c) 1997-2003 by Secret Labs AB.# Copyright (c) 1995-2001 by Fredrik Lundh.## See the README file for information on usage and redistribution.#import refrom . import Image, ImageFile, ImagePalettefrom ._binary import i8__version__ = "0.7"# --------------------------------------------------------------------# Standard tagsCOMMENT = "Comment"DATE = "Date"EQUIPMENT = "Digitalization equipment"FRAMES = "File size (no of images)"LUT = "Lut"NAME = "Name"SCALE = "Scale (x,y)"SIZE = "Image size (x*y)"MODE = "Image type"TAGS = {COMMENT: 0, DATE: 0, EQUIPMENT: 0, FRAMES: 0, LUT: 0, NAME: 0,SCALE: 0, SIZE: 0, MODE: 0}OPEN = {# ifunc93/p3cfunc formats"0 1 image": ("1", "1"),"L 1 image": ("1", "1"),"Greyscale image": ("L", "L"),"Grayscale image": ("L", "L"),"RGB image": ("RGB", "RGB;L"),"RLB image": ("RGB", "RLB"),"RYB image": ("RGB", "RLB"),"B1 image": ("1", "1"),"B2 image": ("P", "P;2"),"B4 image": ("P", "P;4"),"X 24 image": ("RGB", "RGB"),"L 32 S image": ("I", "I;32"),"L 32 F image": ("F", "F;32"),# old p3cfunc formats"RGB3 image": ("RGB", "RGB;T"),"RYB3 image": ("RGB", "RYB;T"),# extensions"LA image": ("LA", "LA;L"),"RGBA image": ("RGBA", "RGBA;L"),"RGBX image": ("RGBX", "RGBX;L"),"CMYK image": ("CMYK", "CMYK;L"),"YCC image": ("YCbCr", "YCbCr;L"),}# ifunc95 extensionsfor i in ["8", "8S", "16", "16S", "32", "32F"]:OPEN["L %s image" % i] = ("F", "F;%s" % i)OPEN["L*%s image" % i] = ("F", "F;%s" % i)for i in ["16", "16L", "16B"]:OPEN["L %s image" % i] = ("I;%s" % i, "I;%s" % i)OPEN["L*%s image" % i] = ("I;%s" % i, "I;%s" % i)for i in ["32S"]:OPEN["L %s image" % i] = ("I", "I;%s" % i)OPEN["L*%s image" % i] = ("I", "I;%s" % i)for i in range(2, 33):OPEN["L*%s image" % i] = ("F", "F;%s" % i)# --------------------------------------------------------------------# Read IM directorysplit = re.compile(br"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")def number(s):try:return int(s)except ValueError:return float(s)### Image plugin for the IFUNC IM file format.class ImImageFile(ImageFile.ImageFile):format = "IM"format_description = "IFUNC Image Memory"_close_exclusive_fp_after_loading = Falsedef _open(self):# Quick rejection: if there's not an LF among the first# 100 bytes, this is (probably) not a text header.if b"\n" not in self.fp.read(100):raise SyntaxError("not an IM file")self.fp.seek(0)n = 0# Default valuesself.info[MODE] = "L"self.info[SIZE] = (512, 512)self.info[FRAMES] = 1self.rawmode = "L"while True:s = self.fp.read(1)# Some versions of IFUNC uses \n\r instead of \r\n...if s == b"\r":continueif not s or s == b'\0' or s == b'\x1A':break# FIXME: this may read whole file if not a text files = s + self.fp.readline()if len(s) > 100:raise SyntaxError("not an IM file")if s[-2:] == b'\r\n':s = s[:-2]elif s[-1:] == b'\n':s = s[:-1]try:m = split.match(s)except re.error as v:raise SyntaxError("not an IM file")if m:k, v = m.group(1, 2)# Don't know if this is the correct encoding,# but a decent guess (I guess)k = k.decode('latin-1', 'replace')v = v.decode('latin-1', 'replace')# Convert value as appropriateif k in [FRAMES, SCALE, SIZE]:v = v.replace("*", ",")v = tuple(map(number, v.split(",")))if len(v) == 1:v = v[0]elif k == MODE and v in OPEN:v, self.rawmode = OPEN[v]# Add to dictionary. Note that COMMENT tags are# combined into a list of strings.if k == COMMENT:if k in self.info:self.info[k].append(v)else:self.info[k] = [v]else:self.info[k] = vif k in TAGS:n += 1else:raise SyntaxError("Syntax error in IM header: " +s.decode('ascii', 'replace'))if not n:raise SyntaxError("Not an IM file")# Basic attributesself.size = self.info[SIZE]self.mode = self.info[MODE]# Skip forward to start of image datawhile s and s[0:1] != b'\x1A':s = self.fp.read(1)if not s:raise SyntaxError("File truncated")if LUT in self.info:# convert lookup table to palette or lut attributepalette = self.fp.read(768)greyscale = 1 # greyscale palettelinear = 1 # linear greyscale palettefor i in range(256):if palette[i] == palette[i+256] == palette[i+512]:if i8(palette[i]) != i:linear = 0else:greyscale = 0if self.mode == "L" or self.mode == "LA":if greyscale:if not linear:self.lut = [i8(c) for c in palette[:256]]else:if self.mode == "L":self.mode = self.rawmode = "P"elif self.mode == "LA":self.mode = self.rawmode = "PA"self.palette = ImagePalette.raw("RGB;L", palette)elif self.mode == "RGB":if not greyscale or not linear:self.lut = [i8(c) for c in palette]self.frame = 0self.__offset = offs = self.fp.tell()self.__fp = self.fp # FIXME: hackif self.rawmode[:2] == "F;":# ifunc95 formatstry:# use bit decoder (if necessary)bits = int(self.rawmode[2:])if bits not in [8, 16, 32]:self.tile = [("bit", (0, 0)+self.size, offs,(bits, 8, 3, 0, -1))]returnexcept ValueError:passif self.rawmode in ["RGB;T", "RYB;T"]:# Old LabEye/3PC files. Would be very surprised if anyone# ever stumbled upon such a file ;-)size = self.size[0] * self.size[1]self.tile = [("raw", (0, 0)+self.size, offs, ("G", 0, -1)),("raw", (0, 0)+self.size, offs+size, ("R", 0, -1)),("raw", (0, 0)+self.size, offs+2*size, ("B", 0, -1))]else:# LabEye/IFUNC filesself.tile = [("raw", (0, 0)+self.size, offs,(self.rawmode, 0, -1))]@propertydef n_frames(self):return self.info[FRAMES]@propertydef is_animated(self):return self.info[FRAMES] > 1def seek(self, frame):if not self._seek_check(frame):returnself.frame = frameif self.mode == "1":bits = 1else:bits = 8 * len(self.mode)size = ((self.size[0] * bits + 7) // 8) * self.size[1]offs = self.__offset + frame * sizeself.fp = self.__fpself.tile = [("raw", (0, 0)+self.size, offs, (self.rawmode, 0, -1))]def tell(self):return self.frame## --------------------------------------------------------------------# Save IM filesSAVE = {# mode: (im type, raw mode)"1": ("0 1", "1"),"L": ("Greyscale", "L"),"LA": ("LA", "LA;L"),"P": ("Greyscale", "P"),"PA": ("LA", "PA;L"),"I": ("L 32S", "I;32S"),"I;16": ("L 16", "I;16"),"I;16L": ("L 16L", "I;16L"),"I;16B": ("L 16B", "I;16B"),"F": ("L 32F", "F;32F"),"RGB": ("RGB", "RGB;L"),"RGBA": ("RGBA", "RGBA;L"),"RGBX": ("RGBX", "RGBX;L"),"CMYK": ("CMYK", "CMYK;L"),"YCbCr": ("YCC", "YCbCr;L")}def _save(im, fp, filename):try:image_type, rawmode = SAVE[im.mode]except KeyError:raise ValueError("Cannot save %s images as IM" % im.mode)frames = im.encoderinfo.get("frames", 1)fp.write(("Image type: %s image\r\n" % image_type).encode('ascii'))if filename:fp.write(("Name: %s\r\n" % filename).encode('ascii'))fp.write(("Image size (x*y): %d*%d\r\n" % im.size).encode('ascii'))fp.write(("File size (no of images): %d\r\n" % frames).encode('ascii'))if im.mode == "P":fp.write(b"Lut: 1\r\n")fp.write(b"\000" * (511-fp.tell()) + b"\032")if im.mode == "P":fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytesImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0, (rawmode, 0, -1))])## --------------------------------------------------------------------# RegistryImage.register_open(ImImageFile.format, ImImageFile)Image.register_save(ImImageFile.format, _save)Image.register_extension(ImImageFile.format, ".im")
123version https://git-lfs.github.com/spec/v1oid sha256:18ad82679e2ac55dbd106898d4c6060954e9d3bfa60fb48e057e164928ed2af5size 9686012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930## The Python Imaging Library.# $Id$## the Image class wrapper## partial release history:# 1995-09-09 fl Created# 1996-03-11 fl PIL release 0.0 (proof of concept)# 1996-04-30 fl PIL release 0.1b1# 1999-07-28 fl PIL release 1.0 final# 2000-06-07 fl PIL release 1.1# 2000-10-20 fl PIL release 1.1.1# 2001-05-07 fl PIL release 1.1.2# 2002-03-15 fl PIL release 1.1.3# 2003-05-10 fl PIL release 1.1.4# 2005-03-28 fl PIL release 1.1.5# 2006-12-02 fl PIL release 1.1.6# 2009-11-15 fl PIL release 1.1.7## Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.# Copyright (c) 1995-2009 by Fredrik Lundh.## See the README file for information on usage and redistribution.## VERSION is deprecated and will be removed in Pillow 6.0.0.# PILLOW_VERSION is deprecated and will be removed after that.# Use __version__ instead.from . import VERSION, PILLOW_VERSION, __version__, _pluginsfrom ._util import py3import loggingimport warningsimport mathlogger = logging.getLogger(__name__)class DecompressionBombWarning(RuntimeWarning):passclass DecompressionBombError(Exception):passclass _imaging_not_installed(object):# module placeholderdef __getattr__(self, id):raise ImportError("The _imaging C module is not installed")# Limit to around a quarter gigabyte for a 24 bit (3 bpp) imageMAX_IMAGE_PIXELS = int(1024 * 1024 * 1024 // 4 // 3)try:# If the _imaging C module is not present, Pillow will not load.# Note that other modules should not refer to _imaging directly;# import Image and use the Image.core variable instead.# Also note that Image.core is not a publicly documented interface,# and should be considered private and subject to change.from . import _imaging as coreif __version__ != getattr(core, 'PILLOW_VERSION', None):raise ImportError("The _imaging extension was built for another ""version of Pillow or PIL:\n""Core version: %s\n""Pillow version: %s" %(getattr(core, 'PILLOW_VERSION', None),__version__))except ImportError as v:core = _imaging_not_installed()# Explanations for ways that we know we might have an import errorif str(v).startswith("Module use of python"):# The _imaging C module is present, but not compiled for# the right version (windows only). Print a warning, if# possible.warnings.warn("The _imaging extension was built for another version ""of Python.",RuntimeWarning)elif str(v).startswith("The _imaging extension"):warnings.warn(str(v), RuntimeWarning)elif "Symbol not found: _PyUnicodeUCS2_" in str(v):# should match _PyUnicodeUCS2_FromString and# _PyUnicodeUCS2_AsLatin1Stringwarnings.warn("The _imaging extension was built for Python with UCS2 support; ""recompile Pillow or build Python --without-wide-unicode. ",RuntimeWarning)elif "Symbol not found: _PyUnicodeUCS4_" in str(v):# should match _PyUnicodeUCS4_FromString and# _PyUnicodeUCS4_AsLatin1Stringwarnings.warn("The _imaging extension was built for Python with UCS4 support; ""recompile Pillow or build Python --with-wide-unicode. ",RuntimeWarning)# Fail here anyway. Don't let people run with a mostly broken Pillow.# see docs/porting.rstraisetry:import builtinsexcept ImportError:import __builtin__builtins = __builtin__from . import ImageModefrom ._binary import i8from ._util import isPath, isStringType, deferred_errorimport osimport sysimport ioimport structimport atexit# type stuffimport numberstry:# Python 3from collections.abc import Callableexcept ImportError:# Python 2.7from collections import Callable# works everywhere, win for pypy, not cpythonUSE_CFFI_ACCESS = hasattr(sys, 'pypy_version_info')try:import cffiHAS_CFFI = Trueexcept ImportError:HAS_CFFI = Falsetry:from pathlib import PathHAS_PATHLIB = Trueexcept ImportError:try:from pathlib2 import PathHAS_PATHLIB = Trueexcept ImportError:HAS_PATHLIB = Falsedef isImageType(t):"""Checks if an object is an image object... warning::This function is for internal use only.:param t: object to check if it's an image:returns: True if the object is an image"""return hasattr(t, "im")## Constants (also defined in _imagingmodule.c!)NONE = 0# transposeFLIP_LEFT_RIGHT = 0FLIP_TOP_BOTTOM = 1ROTATE_90 = 2ROTATE_180 = 3ROTATE_270 = 4TRANSPOSE = 5TRANSVERSE = 6# transformsAFFINE = 0EXTENT = 1PERSPECTIVE = 2QUAD = 3MESH = 4# resampling filtersNEAREST = NONE = 0BOX = 4BILINEAR = LINEAR = 2HAMMING = 5BICUBIC = CUBIC = 3LANCZOS = ANTIALIAS = 1# dithersNEAREST = NONE = 0ORDERED = 1 # Not yet implementedRASTERIZE = 2 # Not yet implementedFLOYDSTEINBERG = 3 # default# palettes/quantizersWEB = 0ADAPTIVE = 1MEDIANCUT = 0MAXCOVERAGE = 1FASTOCTREE = 2LIBIMAGEQUANT = 3# categoriesNORMAL = 0SEQUENCE = 1CONTAINER = 2if hasattr(core, 'DEFAULT_STRATEGY'):DEFAULT_STRATEGY = core.DEFAULT_STRATEGYFILTERED = core.FILTEREDHUFFMAN_ONLY = core.HUFFMAN_ONLYRLE = core.RLEFIXED = core.FIXED# --------------------------------------------------------------------# RegistriesID = []OPEN = {}MIME = {}SAVE = {}SAVE_ALL = {}EXTENSION = {}DECODERS = {}ENCODERS = {}# --------------------------------------------------------------------# Modes supported by this version_MODEINFO = {# NOTE: this table will be removed in future versions. use# getmode* functions or ImageMode descriptors instead.# official modes"1": ("L", "L", ("1",)),"L": ("L", "L", ("L",)),"I": ("L", "I", ("I",)),"F": ("L", "F", ("F",)),"P": ("RGB", "L", ("P",)),"RGB": ("RGB", "L", ("R", "G", "B")),"RGBX": ("RGB", "L", ("R", "G", "B", "X")),"RGBA": ("RGB", "L", ("R", "G", "B", "A")),"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),"LAB": ("RGB", "L", ("L", "A", "B")),"HSV": ("RGB", "L", ("H", "S", "V")),# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and# BGR;24. Use these modes only if you know exactly what you're# doing...}if sys.byteorder == 'little':_ENDIAN = '<'else:_ENDIAN = '>'_MODE_CONV = {# official modes"1": ('|b1', None), # Bits need to be extended to bytes"L": ('|u1', None),"LA": ('|u1', 2),"I": (_ENDIAN + 'i4', None),"F": (_ENDIAN + 'f4', None),"P": ('|u1', None),"RGB": ('|u1', 3),"RGBX": ('|u1', 4),"RGBA": ('|u1', 4),"CMYK": ('|u1', 4),"YCbCr": ('|u1', 3),"LAB": ('|u1', 3), # UNDONE - unsigned |u1i1i1"HSV": ('|u1', 3),# I;16 == I;16L, and I;32 == I;32L"I;16": ('<u2', None),"I;16B": ('>u2', None),"I;16L": ('<u2', None),"I;16S": ('<i2', None),"I;16BS": ('>i2', None),"I;16LS": ('<i2', None),"I;32": ('<u4', None),"I;32B": ('>u4', None),"I;32L": ('<u4', None),"I;32S": ('<i4', None),"I;32BS": ('>i4', None),"I;32LS": ('<i4', None),}def _conv_type_shape(im):typ, extra = _MODE_CONV[im.mode]if extra is None:return (im.size[1], im.size[0]), typelse:return (im.size[1], im.size[0], extra), typMODES = sorted(_MODEINFO)# raw modes that may be memory mapped. NOTE: if you change this, you# may have to modify the stride calculation in map.c too!_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")def getmodebase(mode):"""Gets the "base" mode for given mode. This function returns "L" forimages that contain grayscale data, and "RGB" for images thatcontain color data.:param mode: Input mode.:returns: "L" or "RGB".:exception KeyError: If the input mode was not a standard mode."""return ImageMode.getmode(mode).basemodedef getmodetype(mode):"""Gets the storage type mode. Given a mode, this function returns asingle-layer mode suitable for storing individual bands.:param mode: Input mode.:returns: "L", "I", or "F".:exception KeyError: If the input mode was not a standard mode."""return ImageMode.getmode(mode).basetypedef getmodebandnames(mode):"""Gets a list of individual band names. Given a mode, this function returnsa tuple containing the names of individual bands (use:py:method:`~PIL.Image.getmodetype` to get the mode used to store eachindividual band.:param mode: Input mode.:returns: A tuple containing band names. The length of the tuplegives the number of bands in an image of the given mode.:exception KeyError: If the input mode was not a standard mode."""return ImageMode.getmode(mode).bandsdef getmodebands(mode):"""Gets the number of individual bands for this mode.:param mode: Input mode.:returns: The number of bands in this mode.:exception KeyError: If the input mode was not a standard mode."""return len(ImageMode.getmode(mode).bands)# --------------------------------------------------------------------# Helpers_initialized = 0def preinit():"""Explicitly load standard file format drivers."""global _initializedif _initialized >= 1:returntry:from . import BmpImagePluginexcept ImportError:passtry:from . import GifImagePluginexcept ImportError:passtry:from . import JpegImagePluginexcept ImportError:passtry:from . import PpmImagePluginexcept ImportError:passtry:from . import PngImagePluginexcept ImportError:pass# try:# import TiffImagePlugin# except ImportError:# pass_initialized = 1def init():"""Explicitly initializes the Python Imaging Library. This functionloads all available file format drivers."""global _initializedif _initialized >= 2:return 0for plugin in _plugins:try:logger.debug("Importing %s", plugin)__import__("PIL.%s" % plugin, globals(), locals(), [])except ImportError as e:logger.debug("Image: failed to import %s: %s", plugin, e)if OPEN or SAVE:_initialized = 2return 1# --------------------------------------------------------------------# Codec factories (used by tobytes/frombytes and ImageFile.load)def _getdecoder(mode, decoder_name, args, extra=()):# tweak argumentsif args is None:args = ()elif not isinstance(args, tuple):args = (args,)try:decoder = DECODERS[decoder_name]return decoder(mode, *args + extra)except KeyError:passtry:# get decoderdecoder = getattr(core, decoder_name + "_decoder")# print(decoder, mode, args + extra)return decoder(mode, *args + extra)except AttributeError:raise IOError("decoder %s not available" % decoder_name)def _getencoder(mode, encoder_name, args, extra=()):# tweak argumentsif args is None:args = ()elif not isinstance(args, tuple):args = (args,)try:encoder = ENCODERS[encoder_name]return encoder(mode, *args + extra)except KeyError:passtry:# get encoderencoder = getattr(core, encoder_name + "_encoder")# print(encoder, mode, args + extra)return encoder(mode, *args + extra)except AttributeError:raise IOError("encoder %s not available" % encoder_name)# --------------------------------------------------------------------# Simple expression analyzerdef coerce_e(value):return value if isinstance(value, _E) else _E(value)class _E(object):def __init__(self, data):self.data = datadef __add__(self, other):return _E((self.data, "__add__", coerce_e(other).data))def __mul__(self, other):return _E((self.data, "__mul__", coerce_e(other).data))def _getscaleoffset(expr):stub = ["stub"]data = expr(_E(stub)).datatry:(a, b, c) = data # simplified syntaxif (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):return c, 0.0if a is stub and b == "__add__" and isinstance(c, numbers.Number):return 1.0, cexcept TypeError:passtry:((a, b, c), d, e) = data # full syntaxif (a is stub and b == "__mul__" and isinstance(c, numbers.Number) andd == "__add__" and isinstance(e, numbers.Number)):return c, eexcept TypeError:passraise ValueError("illegal expression")# --------------------------------------------------------------------# Implementation wrapperclass Image(object):"""This class represents an image object. To create:py:class:`~PIL.Image.Image` objects, use the appropriate factoryfunctions. There's hardly ever any reason to call the Image constructordirectly.* :py:func:`~PIL.Image.open`* :py:func:`~PIL.Image.new`* :py:func:`~PIL.Image.frombytes`"""format = Noneformat_description = None_close_exclusive_fp_after_loading = Truedef __init__(self):# FIXME: take "new" parameters / other image?# FIXME: turn mode and size into delegating properties?self.im = Noneself.mode = ""self.size = (0, 0)self.palette = Noneself.info = {}self.category = NORMALself.readonly = 0self.pyaccess = None@propertydef width(self):return self.size[0]@propertydef height(self):return self.size[1]def _new(self, im):new = Image()new.im = imnew.mode = im.modenew.size = im.sizeif im.mode in ('P', 'PA'):if self.palette:new.palette = self.palette.copy()else:from . import ImagePalettenew.palette = ImagePalette.ImagePalette()new.info = self.info.copy()return new# Context Manager Supportdef __enter__(self):return selfdef __exit__(self, *args):self.close()def close(self):"""Closes the file pointer, if possible.This operation will destroy the image core and release its memory.The image data will be unusable afterward.This function is only required to close images that have nothad their file read and closed by the:py:meth:`~PIL.Image.Image.load` method. See:ref:`file-handling` for more information."""try:self.fp.close()self.fp = Noneexcept Exception as msg:logger.debug("Error closing: %s", msg)if getattr(self, 'map', None):self.map = None# Instead of simply setting to None, we're setting up a# deferred error that will better explain that the core image# object is gone.self.im = deferred_error(ValueError("Operation on closed image"))if sys.version_info.major >= 3:def __del__(self):if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp')and self.fp and self._exclusive_fp):self.fp.close()self.fp = Nonedef _copy(self):self.load()self.im = self.im.copy()self.pyaccess = Noneself.readonly = 0def _ensure_mutable(self):if self.readonly:self._copy()else:self.load()def _dump(self, file=None, format=None, **options):import tempfilesuffix = ''if format:suffix = '.'+formatif not file:f, filename = tempfile.mkstemp(suffix)os.close(f)else:filename = fileif not filename.endswith(suffix):filename = filename + suffixself.load()if not format or format == "PPM":self.im.save_ppm(filename)else:self.save(filename, format, **options)return filenamedef __eq__(self, other):return (isinstance(other, Image) andself.__class__.__name__ == other.__class__.__name__ andself.mode == other.mode andself.size == other.size andself.info == other.info andself.category == other.category andself.readonly == other.readonly andself.getpalette() == other.getpalette() andself.tobytes() == other.tobytes())def __ne__(self, other):eq = (self == other)return not eqdef __repr__(self):return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (self.__class__.__module__, self.__class__.__name__,self.mode, self.size[0], self.size[1],id(self))def _repr_png_(self):""" iPython display hook support:returns: png version of the image as bytes"""from io import BytesIOb = BytesIO()self.save(b, 'PNG')return b.getvalue()@propertydef __array_interface__(self):# numpy array interface supportnew = {}shape, typestr = _conv_type_shape(self)new['shape'] = shapenew['typestr'] = typestrnew['version'] = 3if self.mode == '1':# Binary images need to be extended from bits to bytes# See: https://github.com/python-pillow/Pillow/issues/350new['data'] = self.tobytes('raw', 'L')else:new['data'] = self.tobytes()return newdef __getstate__(self):return [self.info,self.mode,self.size,self.getpalette(),self.tobytes()]def __setstate__(self, state):Image.__init__(self)self.tile = []info, mode, size, palette, data = stateself.info = infoself.mode = modeself.size = sizeself.im = core.new(mode, size)if mode in ("L", "P") and palette:self.putpalette(palette)self.frombytes(data)def tobytes(self, encoder_name="raw", *args):"""Return image as a bytes object... warning::This method returns the raw image data from the internalstorage. For compressed image data (e.g. PNG, JPEG) use:meth:`~.save`, with a BytesIO parameter for in-memorydata.:param encoder_name: What encoder to use. The default is touse the standard "raw" encoder.:param args: Extra arguments to the encoder.:rtype: A bytes object."""# may pass tuple instead of argument listif len(args) == 1 and isinstance(args[0], tuple):args = args[0]if encoder_name == "raw" and args == ():args = self.modeself.load()# unpack datae = _getencoder(self.mode, encoder_name, args)e.setimage(self.im)bufsize = max(65536, self.size[0] * 4) # see RawEncode.cdata = []while True:l, s, d = e.encode(bufsize)data.append(d)if s:breakif s < 0:raise RuntimeError("encoder error %d in tobytes" % s)return b"".join(data)def tostring(self, *args, **kw):raise NotImplementedError("tostring() has been removed. ""Please call tobytes() instead.")def tobitmap(self, name="image"):"""Returns the image converted to an X11 bitmap... note:: This method only works for mode "1" images.:param name: The name prefix to use for the bitmap variables.:returns: A string containing an X11 bitmap.:raises ValueError: If the mode is not "1""""self.load()if self.mode != "1":raise ValueError("not a bitmap")data = self.tobytes("xbm")return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),("#define %s_height %d\n" % (name, self.size[1])).encode('ascii'),("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])def frombytes(self, data, decoder_name="raw", *args):"""Loads this image with pixel data from a bytes object.This method is similar to the :py:func:`~PIL.Image.frombytes` function,but loads data into this image instead of creating a new image object."""# may pass tuple instead of argument listif len(args) == 1 and isinstance(args[0], tuple):args = args[0]# default formatif decoder_name == "raw" and args == ():args = self.mode# unpack datad = _getdecoder(self.mode, decoder_name, args)d.setimage(self.im)s = d.decode(data)if s[0] >= 0:raise ValueError("not enough image data")if s[1] != 0:raise ValueError("cannot decode image data")def fromstring(self, *args, **kw):raise NotImplementedError("fromstring() has been removed. ""Please call frombytes() instead.")def load(self):"""Allocates storage for the image and loads the pixel data. Innormal cases, you don't need to call this method, since theImage class automatically loads an opened image when it isaccessed for the first time.This method will close the file associated with the image. See:ref:`file-handling` for more information.:returns: An image access object.:rtype: :ref:`PixelAccess` or :py:class:`PIL.PyAccess`"""if self.im and self.palette and self.palette.dirty:# realize paletteself.im.putpalette(*self.palette.getdata())self.palette.dirty = 0self.palette.mode = "RGB"self.palette.rawmode = Noneif "transparency" in self.info:if isinstance(self.info["transparency"], int):self.im.putpalettealpha(self.info["transparency"], 0)else:self.im.putpalettealphas(self.info["transparency"])self.palette.mode = "RGBA"if self.im:if HAS_CFFI and USE_CFFI_ACCESS:if self.pyaccess:return self.pyaccessfrom . import PyAccessself.pyaccess = PyAccess.new(self, self.readonly)if self.pyaccess:return self.pyaccessreturn self.im.pixel_access(self.readonly)def verify(self):"""Verifies the contents of a file. For data read from a file, thismethod attempts to determine if the file is broken, withoutactually decoding the image data. If this method finds anyproblems, it raises suitable exceptions. If you need to loadthe image after using this method, you must reopen the imagefile."""passdef convert(self, mode=None, matrix=None, dither=None,palette=WEB, colors=256):"""Returns a converted copy of this image. For the "P" mode, thismethod translates pixels through the palette. If mode isomitted, a mode is chosen so that all information in the imageand the palette can be represented without a palette.The current version supports all possible conversions between"L", "RGB" and "CMYK." The **matrix** argument only supports "L"and "RGB".When translating a color image to black and white (mode "L"),the library uses the ITU-R 601-2 luma transform::L = R * 299/1000 + G * 587/1000 + B * 114/1000The default method of converting a greyscale ("L") or "RGB"image into a bilevel (mode "1") image uses Floyd-Steinbergdither to approximate the original image luminosity levels. Ifdither is NONE, all non-zero values are set to 255 (white). Touse other thresholds, use the :py:meth:`~PIL.Image.Image.point`method.:param mode: The requested mode. See: :ref:`concept-modes`.:param matrix: An optional conversion matrix. If given, thisshould be 4- or 12-tuple containing floating point values.:param dither: Dithering method, used when converting frommode "RGB" to "P" or from "RGB" or "L" to "1".Available methods are NONE or FLOYDSTEINBERG (default).:param palette: Palette to use when converting from mode "RGB"to "P". Available palettes are WEB or ADAPTIVE.:param colors: Number of colors to use for the ADAPTIVE palette.Defaults to 256.:rtype: :py:class:`~PIL.Image.Image`:returns: An :py:class:`~PIL.Image.Image` object."""self.load()if not mode and self.mode == "P":# determine default modeif self.palette:mode = self.palette.modeelse:mode = "RGB"if not mode or (mode == self.mode and not matrix):return self.copy()if matrix:# matrix conversionif mode not in ("L", "RGB"):raise ValueError("illegal conversion")im = self.im.convert_matrix(mode, matrix)return self._new(im)if mode == "P" and self.mode == "RGBA":return self.quantize(colors)trns = Nonedelete_trns = False# transparency handlingif "transparency" in self.info and \self.info['transparency'] is not None:if self.mode in ('L', 'RGB') and mode == 'RGBA':# Use transparent conversion to promote from transparent# color to an alpha channel.new_im = self._new(self.im.convert_transparent(mode, self.info['transparency']))del(new_im.info['transparency'])return new_imelif self.mode in ('L', 'RGB', 'P') and mode in ('L', 'RGB', 'P'):t = self.info['transparency']if isinstance(t, bytes):# Dragons. This can't be represented by a single colorwarnings.warn('Palette images with Transparency ' +' expressed in bytes should be converted ' +'to RGBA images')delete_trns = Trueelse:# get the new transparency color.# use existing conversionstrns_im = Image()._new(core.new(self.mode, (1, 1)))if self.mode == 'P':trns_im.putpalette(self.palette)if isinstance(t, tuple):try:t = trns_im.palette.getcolor(t)except:raise ValueError("Couldn't allocate a palette ""color for transparency")trns_im.putpixel((0, 0), t)if mode in ('L', 'RGB'):trns_im = trns_im.convert(mode)else:# can't just retrieve the palette number, got to do it# after quantization.trns_im = trns_im.convert('RGB')trns = trns_im.getpixel((0, 0))elif self.mode == 'P' and mode == 'RGBA':t = self.info['transparency']delete_trns = Trueif isinstance(t, bytes):self.im.putpalettealphas(t)elif isinstance(t, int):self.im.putpalettealpha(t, 0)else:raise ValueError("Transparency for P mode should" +" be bytes or int")if mode == "P" and palette == ADAPTIVE:im = self.im.quantize(colors)new = self._new(im)from . import ImagePalettenew.palette = ImagePalette.raw("RGB", new.im.getpalette("RGB"))if delete_trns:# This could possibly happen if we requantize to fewer colors.# The transparency would be totally off in that case.del(new.info['transparency'])if trns is not None:try:new.info['transparency'] = new.palette.getcolor(trns)except:# if we can't make a transparent color, don't leave the old# transparency hanging around to mess us up.del(new.info['transparency'])warnings.warn("Couldn't allocate palette entry " +"for transparency")return new# colorspace conversionif dither is None:dither = FLOYDSTEINBERGtry:im = self.im.convert(mode, dither)except ValueError:try:# normalize source image and try againim = self.im.convert(getmodebase(self.mode))im = im.convert(mode, dither)except KeyError:raise ValueError("illegal conversion")new_im = self._new(im)if delete_trns:# crash fail if we leave a bytes transparency in an rgb/l mode.del(new_im.info['transparency'])if trns is not None:if new_im.mode == 'P':try:new_im.info['transparency'] = new_im.palette.getcolor(trns)except:del(new_im.info['transparency'])warnings.warn("Couldn't allocate palette entry " +"for transparency")else:new_im.info['transparency'] = trnsreturn new_imdef quantize(self, colors=256, method=None, kmeans=0, palette=None):"""Convert the image to 'P' mode with the specified numberof colors.:param colors: The desired number of colors, <= 256:param method: 0 = median cut1 = maximum coverage2 = fast octree3 = libimagequant:param kmeans: Integer:param palette: Quantize to the palette of given :py:class:`PIL.Image.Image`.:returns: A new image"""self.load()if method is None:# defaults:method = 0if self.mode == 'RGBA':method = 2if self.mode == 'RGBA' and method not in (2, 3):# Caller specified an invalid mode.raise ValueError('Fast Octree (method == 2) and libimagequant (method == 3) ' +'are the only valid methods for quantizing RGBA images')if palette:# use palette from reference imagepalette.load()if palette.mode != "P":raise ValueError("bad mode for palette image")if self.mode != "RGB" and self.mode != "L":raise ValueError("only RGB or L mode images can be quantized to a palette")im = self.im.convert("P", 1, palette.im)return self._new(im)return self._new(self.im.quantize(colors, method, kmeans))def copy(self):"""Copies this image. Use this method if you wish to paste thingsinto an image, but still retain the original.:rtype: :py:class:`~PIL.Image.Image`:returns: An :py:class:`~PIL.Image.Image` object."""self.load()return self._new(self.im.copy())__copy__ = copydef crop(self, box=None):"""Returns a rectangular region from this image. The box is a4-tuple defining the left, upper, right, and lower pixelcoordinate. See :ref:`coordinate-system`.Note: Prior to Pillow 3.4.0, this was a lazy operation.:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.:rtype: :py:class:`~PIL.Image.Image`:returns: An :py:class:`~PIL.Image.Image` object."""if box is None:return self.copy()self.load()return self._new(self._crop(self.im, box))def _crop(self, im, box):"""Returns a rectangular region from the core image object im.This is equivalent to calling im.crop((x0, y0, x1, y1)), butincludes additional sanity checks.:param im: a core image object:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.:returns: A core image object."""x0, y0, x1, y1 = map(int, map(round, box))if x1 < x0:x1 = x0if y1 < y0:y1 = y0_decompression_bomb_check((x1, y1))return im.crop((x0, y0, x1, y1))def draft(self, mode, size):"""Configures the image file loader so it returns a version of theimage that as closely as possible matches the given mode andsize. For example, you can use this method to convert a colorJPEG to greyscale while loading it, or to extract a 128x192version from a PCD file.Note that this method modifies the :py:class:`~PIL.Image.Image` objectin place. If the image has already been loaded, this method has noeffect.Note: This method is not implemented for most images. It iscurrently implemented only for JPEG and PCD images.:param mode: The requested mode.:param size: The requested size."""passdef _expand(self, xmargin, ymargin=None):if ymargin is None:ymargin = xmarginself.load()return self._new(self.im.expand(xmargin, ymargin, 0))def filter(self, filter):"""Filters this image using the given filter. For a list ofavailable filters, see the :py:mod:`~PIL.ImageFilter` module.:param filter: Filter kernel.:returns: An :py:class:`~PIL.Image.Image` object. """from . import ImageFilterself.load()if isinstance(filter, Callable):filter = filter()if not hasattr(filter, "filter"):raise TypeError("filter argument should be ImageFilter.Filter " +"instance or class")multiband = isinstance(filter, ImageFilter.MultibandFilter)if self.im.bands == 1 or multiband:return self._new(filter.filter(self.im))ims = []for c in range(self.im.bands):ims.append(self._new(filter.filter(self.im.getband(c))))return merge(self.mode, ims)def getbands(self):"""Returns a tuple containing the name of each band in this image.For example, **getbands** on an RGB image returns ("R", "G", "B").:returns: A tuple containing band names.:rtype: tuple"""return ImageMode.getmode(self.mode).bandsdef getbbox(self):"""Calculates the bounding box of the non-zero regions in theimage.:returns: The bounding box is returned as a 4-tuple defining theleft, upper, right, and lower pixel coordinate. See:ref:`coordinate-system`. If the image is completely empty, thismethod returns None."""self.load()return self.im.getbbox()def getcolors(self, maxcolors=256):"""Returns a list of colors used in this image.:param maxcolors: Maximum number of colors. If this number isexceeded, this method returns None. The default limit is256 colors.:returns: An unsorted list of (count, pixel) values."""self.load()if self.mode in ("1", "L", "P"):h = self.im.histogram()out = []for i in range(256):if h[i]:out.append((h[i], i))if len(out) > maxcolors:return Nonereturn outreturn self.im.getcolors(maxcolors)def getdata(self, band=None):"""Returns the contents of this image as a sequence objectcontaining pixel values. The sequence object is flattened, sothat values for line one follow directly after the values ofline zero, and so on.Note that the sequence object returned by this method is aninternal PIL data type, which only supports certain sequenceoperations. To convert it to an ordinary sequence (e.g. forprinting), use **list(im.getdata())**.:param band: What band to return. The default is to returnall bands. To return a single band, pass in the indexvalue (e.g. 0 to get the "R" band from an "RGB" image).:returns: A sequence-like object."""self.load()if band is not None:return self.im.getband(band)return self.im # could be abuseddef getextrema(self):"""Gets the the minimum and maximum pixel values for each band inthe image.:returns: For a single-band image, a 2-tuple containing theminimum and maximum pixel value. For a multi-band image,a tuple containing one 2-tuple for each band."""self.load()if self.im.bands > 1:extrema = []for i in range(self.im.bands):extrema.append(self.im.getband(i).getextrema())return tuple(extrema)return self.im.getextrema()def getim(self):"""Returns a capsule that points to the internal image memory.:returns: A capsule object."""self.load()return self.im.ptrdef getpalette(self):"""Returns the image palette as a list.:returns: A list of color values [r, g, b, ...], or None if theimage has no palette."""self.load()try:if py3:return list(self.im.getpalette())else:return [i8(c) for c in self.im.getpalette()]except ValueError:return None # no palettedef getpixel(self, xy):"""Returns the pixel value at a given position.:param xy: The coordinate, given as (x, y). See:ref:`coordinate-system`.:returns: The pixel value. If the image is a multi-layer image,this method returns a tuple."""self.load()if self.pyaccess:return self.pyaccess.getpixel(xy)return self.im.getpixel(xy)def getprojection(self):"""Get projection to x and y axes:returns: Two sequences, indicating where there are non-zeropixels along the X-axis and the Y-axis, respectively."""self.load()x, y = self.im.getprojection()return [i8(c) for c in x], [i8(c) for c in y]def histogram(self, mask=None, extrema=None):"""Returns a histogram for the image. The histogram is returned asa list of pixel counts, one for each pixel value in the sourceimage. If the image has more than one band, the histograms forall bands are concatenated (for example, the histogram for an"RGB" image contains 768 values).A bilevel image (mode "1") is treated as a greyscale ("L") imageby this method.If a mask is provided, the method returns a histogram for thoseparts of the image where the mask image is non-zero. The maskimage must have the same size as the image, and be either abi-level image (mode "1") or a greyscale image ("L").:param mask: An optional mask.:returns: A list containing pixel counts."""self.load()if mask:mask.load()return self.im.histogram((0, 0), mask.im)if self.mode in ("I", "F"):if extrema is None:extrema = self.getextrema()return self.im.histogram(extrema)return self.im.histogram()def offset(self, xoffset, yoffset=None):raise NotImplementedError("offset() has been removed. ""Please call ImageChops.offset() instead.")def paste(self, im, box=None, mask=None):"""Pastes another image into this image. The box argument is eithera 2-tuple giving the upper left corner, a 4-tuple defining theleft, upper, right, and lower pixel coordinate, or None (same as(0, 0)). See :ref:`coordinate-system`. If a 4-tuple is given, the sizeof the pasted image must match the size of the region.If the modes don't match, the pasted image is converted to the mode ofthis image (see the :py:meth:`~PIL.Image.Image.convert` method fordetails).Instead of an image, the source can be a integer or tuplecontaining pixel values. The method then fills the regionwith the given color. When creating RGB images, you canalso use color strings as supported by the ImageColor module.If a mask is given, this method updates only the regionsindicated by the mask. You can use either "1", "L" or "RGBA"images (in the latter case, the alpha band is used as mask).Where the mask is 255, the given image is copied as is. Wherethe mask is 0, the current value is preserved. Intermediatevalues will mix the two images together, including their alphachannels if they have them.See :py:meth:`~PIL.Image.Image.alpha_composite` if you want tocombine images with respect to their alpha channels.:param im: Source image or pixel value (integer or tuple).:param box: An optional 4-tuple giving the region to paste into.If a 2-tuple is used instead, it's treated as the upper leftcorner. If omitted or None, the source is pasted into theupper left corner.If an image is given as the second argument and there is nothird, the box defaults to (0, 0), and the second argumentis interpreted as a mask image.:param mask: An optional mask image."""if isImageType(box) and mask is None:# abbreviated paste(im, mask) syntaxmask = boxbox = Noneif box is None:box = (0, 0)if len(box) == 2:# upper left corner given; get size from image or maskif isImageType(im):size = im.sizeelif isImageType(mask):size = mask.sizeelse:# FIXME: use self.size here?raise ValueError("cannot determine region size; use 4-item box")box += (box[0]+size[0], box[1]+size[1])if isStringType(im):from . import ImageColorim = ImageColor.getcolor(im, self.mode)elif isImageType(im):im.load()if self.mode != im.mode:if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):# should use an adapter for this!im = im.convert(self.mode)im = im.imself._ensure_mutable()if mask:mask.load()self.im.paste(im, box, mask.im)else:self.im.paste(im, box)def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):""" 'In-place' analog of Image.alpha_composite. Composites an imageonto this image.:param im: image to composite over this one:param dest: Optional 2 tuple (left, top) specifying the upperleft corner in this (destination) image.:param source: Optional 2 (left, top) tuple for the upper leftcorner in the overlay source image, or 4 tuple (left, top, right,bottom) for the bounds of the source rectanglePerformance Note: Not currently implemented in-place in the core layer."""if not isinstance(source, (list, tuple)):raise ValueError("Source must be a tuple")if not isinstance(dest, (list, tuple)):raise ValueError("Destination must be a tuple")if not len(source) in (2, 4):raise ValueError("Source must be a 2 or 4-tuple")if not len(dest) == 2:raise ValueError("Destination must be a 2-tuple")if min(source) < 0:raise ValueError("Source must be non-negative")if min(dest) < 0:raise ValueError("Destination must be non-negative")if len(source) == 2:source = source + im.size# over image, crop if it's not the whole thing.if source == (0, 0) + im.size:overlay = imelse:overlay = im.crop(source)# target for the pastebox = dest + (dest[0] + overlay.width, dest[1] + overlay.height)# destination image. don't copy if we're using the whole image.if box == (0, 0) + self.size:background = selfelse:background = self.crop(box)result = alpha_composite(background, overlay)self.paste(result, box)def point(self, lut, mode=None):"""Maps this image through a lookup table or function.:param lut: A lookup table, containing 256 (or 65536 ifself.mode=="I" and mode == "L") values per band in theimage. A function can be used instead, it should take asingle argument. The function is called once for eachpossible pixel value, and the resulting table is applied toall bands of the image.:param mode: Output mode (default is same as input). In thecurrent version, this can only be used if the source imagehas mode "L" or "P", and the output has mode "1" or thesource image mode is "I" and the output mode is "L".:returns: An :py:class:`~PIL.Image.Image` object."""self.load()if isinstance(lut, ImagePointHandler):return lut.point(self)if callable(lut):# if it isn't a list, it should be a functionif self.mode in ("I", "I;16", "F"):# check if the function can be used with point_transform# UNDONE wiredfool -- I think this prevents us from ever doing# a gamma function point transform on > 8bit images.scale, offset = _getscaleoffset(lut)return self._new(self.im.point_transform(scale, offset))# for other modes, convert the function to a tablelut = [lut(i) for i in range(256)] * self.im.bandsif self.mode == "F":# FIXME: _imaging returns a confusing error message for this caseraise ValueError("point operation not supported for this mode")return self._new(self.im.point(lut, mode))def putalpha(self, alpha):"""Adds or replaces the alpha layer in this image. If the imagedoes not have an alpha layer, it's converted to "LA" or "RGBA".The new layer must be either "L" or "1".:param alpha: The new alpha layer. This can either be an "L" or "1"image having the same size as this image, or an integer orother color value."""self._ensure_mutable()if self.mode not in ("LA", "RGBA"):# attempt to promote self to a matching alpha modetry:mode = getmodebase(self.mode) + "A"try:self.im.setmode(mode)except (AttributeError, ValueError):# do things the hard wayim = self.im.convert(mode)if im.mode not in ("LA", "RGBA"):raise ValueError # sanity checkself.im = imself.pyaccess = Noneself.mode = self.im.modeexcept (KeyError, ValueError):raise ValueError("illegal image mode")if self.mode == "LA":band = 1else:band = 3if isImageType(alpha):# alpha layerif alpha.mode not in ("1", "L"):raise ValueError("illegal image mode")alpha.load()if alpha.mode == "1":alpha = alpha.convert("L")else:# constant alphatry:self.im.fillband(band, alpha)except (AttributeError, ValueError):# do things the hard wayalpha = new("L", self.size, alpha)else:returnself.im.putband(alpha.im, band)def putdata(self, data, scale=1.0, offset=0.0):"""Copies pixel data to this image. This method copies data from asequence object into the image, starting at the upper leftcorner (0, 0), and continuing until either the image or thesequence ends. The scale and offset values are used to adjustthe sequence values: **pixel = value*scale + offset**.:param data: A sequence object.:param scale: An optional scale value. The default is 1.0.:param offset: An optional offset value. The default is 0.0."""self._ensure_mutable()self.im.putdata(data, scale, offset)def putpalette(self, data, rawmode="RGB"):"""Attaches a palette to this image. The image must be a "P" or"L" image, and the palette sequence must contain 768 integervalues, where each group of three values represent the red,green, and blue values for the corresponding pixelindex. Instead of an integer sequence, you can use an 8-bitstring.:param data: A palette sequence (either a list or a string).:param rawmode: The raw mode of the palette."""from . import ImagePaletteif self.mode not in ("L", "P"):raise ValueError("illegal image mode")self.load()if isinstance(data, ImagePalette.ImagePalette):palette = ImagePalette.raw(data.rawmode, data.palette)else:if not isinstance(data, bytes):if py3:data = bytes(data)else:data = "".join(chr(x) for x in data)palette = ImagePalette.raw(rawmode, data)self.mode = "P"self.palette = paletteself.palette.mode = "RGB"self.load() # install new palettedef putpixel(self, xy, value):"""Modifies the pixel at the given position. The color is given asa single numerical value for single-band images, and a tuple formulti-band images.Note that this method is relatively slow. For more extensive changes,use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`module instead.See:* :py:meth:`~PIL.Image.Image.paste`* :py:meth:`~PIL.Image.Image.putdata`* :py:mod:`~PIL.ImageDraw`:param xy: The pixel coordinate, given as (x, y). See:ref:`coordinate-system`.:param value: The pixel value."""if self.readonly:self._copy()self.load()if self.pyaccess:return self.pyaccess.putpixel(xy, value)return self.im.putpixel(xy, value)def remap_palette(self, dest_map, source_palette=None):"""Rewrites the image to reorder the palette.:param dest_map: A list of indexes into the original palette.e.g. [1,0] would swap a two item palette, and list(range(255))is the identity transform.:param source_palette: Bytes or None.:returns: An :py:class:`~PIL.Image.Image` object."""from . import ImagePaletteif self.mode not in ("L", "P"):raise ValueError("illegal image mode")if source_palette is None:if self.mode == "P":real_source_palette = self.im.getpalette("RGB")[:768]else: # L-modereal_source_palette = bytearray(i//3 for i in range(768))else:real_source_palette = source_palettepalette_bytes = b""new_positions = [0]*256# pick only the used colors from the palettefor i, oldPosition in enumerate(dest_map):palette_bytes += real_source_palette[oldPosition*3:oldPosition*3+3]new_positions[oldPosition] = i# replace the palette color id of all pixel with the new id# Palette images are [0..255], mapped through a 1 or 3# byte/color map. We need to remap the whole image# from palette 1 to palette 2. New_positions is# an array of indexes into palette 1. Palette 2 is# palette 1 with any holes removed.# We're going to leverage the convert mechanism to use the# C code to remap the image from palette 1 to palette 2,# by forcing the source image into 'L' mode and adding a# mapping 'L' mode palette, then converting back to 'L'# sans palette thus converting the image bytes, then# assigning the optimized RGB palette.# perf reference, 9500x4000 gif, w/~135 colors# 14 sec prepatch, 1 sec postpatch with optimization forced.mapping_palette = bytearray(new_positions)m_im = self.copy()m_im.mode = 'P'm_im.palette = ImagePalette.ImagePalette("RGB",palette=mapping_palette*3,size=768)# possibly set palette dirty, then# m_im.putpalette(mapping_palette, 'L') # converts to 'P'# or just force it.# UNDONE -- this is part of the general issue with palettesm_im.im.putpalette(*m_im.palette.getdata())m_im = m_im.convert('L')# Internally, we require 768 bytes for a palette.new_palette_bytes = (palette_bytes +(768 - len(palette_bytes)) * b'\x00')m_im.putpalette(new_palette_bytes)m_im.palette = ImagePalette.ImagePalette("RGB",palette=palette_bytes,size=len(palette_bytes))return m_imdef resize(self, size, resample=NEAREST, box=None):"""Returns a resized copy of this image.:param size: The requested size in pixels, as a 2-tuple:(width, height).:param resample: An optional resampling filter. This can beone of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,:py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,:py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.If omitted, or if the image has mode "1" or "P", it isset :py:attr:`PIL.Image.NEAREST`.See: :ref:`concept-filters`.:param box: An optional 4-tuple of floats giving the regionof the source image which should be scaled.The values should be within (0, 0, width, height) rectangle.If omitted or None, the entire source is used.:returns: An :py:class:`~PIL.Image.Image` object."""if resample not in (NEAREST, BILINEAR, BICUBIC, LANCZOS, BOX, HAMMING,):raise ValueError("unknown resampling filter")size = tuple(size)if box is None:box = (0, 0) + self.sizeelse:box = tuple(box)if self.size == size and box == (0, 0) + self.size:return self.copy()if self.mode in ("1", "P"):resample = NEARESTif self.mode == 'LA':return self.convert('La').resize(size, resample, box).convert('LA')if self.mode == 'RGBA':return self.convert('RGBa').resize(size, resample, box).convert('RGBA')self.load()return self._new(self.im.resize(size, resample, box))def rotate(self, angle, resample=NEAREST, expand=0, center=None,translate=None, fillcolor=None):"""Returns a rotated copy of this image. This method returns acopy of this image, rotated the given number of degrees counterclockwise around its centre.:param angle: In degrees counter clockwise.:param resample: An optional resampling filter. This can beone of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2environment), or :py:attr:`PIL.Image.BICUBIC`(cubic spline interpolation in a 4x4 environment).If omitted, or if the image has mode "1" or "P", it isset :py:attr:`PIL.Image.NEAREST`. See :ref:`concept-filters`.:param expand: Optional expansion flag. If true, expands the outputimage to make it large enough to hold the entire rotated image.If false or omitted, make the output image the same size as theinput image. Note that the expand flag assumes rotation aroundthe center and no translation.:param center: Optional center of rotation (a 2-tuple). Origin isthe upper left corner. Default is the center of the image.:param translate: An optional post-rotate translation (a 2-tuple).:param fillcolor: An optional color for area outside the rotated image.:returns: An :py:class:`~PIL.Image.Image` object."""angle = angle % 360.0# Fast paths regardless of filter, as long as we're not# translating or changing the center.if not (center or translate):if angle == 0:return self.copy()if angle == 180:return self.transpose(ROTATE_180)if angle == 90 and expand:return self.transpose(ROTATE_90)if angle == 270 and expand:return self.transpose(ROTATE_270)# Calculate the affine matrix. Note that this is the reverse# transformation (from destination image to source) because we# want to interpolate the (discrete) destination pixel from# the local area around the (floating) source pixel.# The matrix we actually want (note that it operates from the right):# (1, 0, tx) (1, 0, cx) ( cos a, sin a, 0) (1, 0, -cx)# (0, 1, ty) * (0, 1, cy) * (-sin a, cos a, 0) * (0, 1, -cy)# (0, 0, 1) (0, 0, 1) ( 0, 0, 1) (0, 0, 1)# The reverse matrix is thus:# (1, 0, cx) ( cos -a, sin -a, 0) (1, 0, -cx) (1, 0, -tx)# (0, 1, cy) * (-sin -a, cos -a, 0) * (0, 1, -cy) * (0, 1, -ty)# (0, 0, 1) ( 0, 0, 1) (0, 0, 1) (0, 0, 1)# In any case, the final translation may be updated at the end to# compensate for the expand flag.w, h = self.sizeif translate is None:post_trans = (0, 0)else:post_trans = translateif center is None:rotn_center = (w / 2.0, h / 2.0) # FIXME These should be rounded to ints?else:rotn_center = centerangle = - math.radians(angle)matrix = [round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0,round(-math.sin(angle), 15), round(math.cos(angle), 15), 0.0]def transform(x, y, matrix):(a, b, c, d, e, f) = matrixreturn a*x + b*y + c, d*x + e*y + fmatrix[2], matrix[5] = transform(-rotn_center[0] - post_trans[0],-rotn_center[1] - post_trans[1], matrix)matrix[2] += rotn_center[0]matrix[5] += rotn_center[1]if expand:# calculate output sizexx = []yy = []for x, y in ((0, 0), (w, 0), (w, h), (0, h)):x, y = transform(x, y, matrix)xx.append(x)yy.append(y)nw = int(math.ceil(max(xx)) - math.floor(min(xx)))nh = int(math.ceil(max(yy)) - math.floor(min(yy)))# We multiply a translation matrix from the right. Because of its# special form, this is the same as taking the image of the# translation vector as new translation vector.matrix[2], matrix[5] = transform(-(nw - w) / 2.0,-(nh - h) / 2.0,matrix)w, h = nw, nhreturn self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)def save(self, fp, format=None, **params):"""Saves this image under the given filename. If no format isspecified, the format to use is determined from the filenameextension, if possible.Keyword options can be used to provide additional instructionsto the writer. If a writer doesn't recognise an option, it issilently ignored. The available options are described in the:doc:`image format documentation<../handbook/image-file-formats>` for each writer.You can use a file object instead of a filename. In this case,you must always specify the format. The file object mustimplement the ``seek``, ``tell``, and ``write``methods, and be opened in binary mode.:param fp: A filename (string), pathlib.Path object or file object.:param format: Optional format override. If omitted, theformat to use is determined from the filename extension.If a file object was used instead of a filename, thisparameter should always be used.:param params: Extra parameters to the image writer.:returns: None:exception KeyError: If the output format could not be determinedfrom the file name. Use the format option to solve this.:exception IOError: If the file could not be written. The filemay have been created, and may contain partial data."""filename = ""open_fp = Falseif isPath(fp):filename = fpopen_fp = Trueelif HAS_PATHLIB and isinstance(fp, Path):filename = str(fp)open_fp = Trueif not filename and hasattr(fp, "name") and isPath(fp.name):# only set the name for metadata purposesfilename = fp.name# may mutate self!self.load()save_all = params.pop('save_all', False)self.encoderinfo = paramsself.encoderconfig = ()preinit()ext = os.path.splitext(filename)[1].lower()if not format:if ext not in EXTENSION:init()try:format = EXTENSION[ext]except KeyError:raise ValueError('unknown file extension: {}'.format(ext))if format.upper() not in SAVE:init()if save_all:save_handler = SAVE_ALL[format.upper()]else:save_handler = SAVE[format.upper()]if open_fp:if params.get('append', False):fp = builtins.open(filename, "r+b")else:# Open also for reading ("+"), because TIFF save_all# writer needs to go back and edit the written data.fp = builtins.open(filename, "w+b")try:save_handler(self, fp, filename)finally:# do what we can to clean upif open_fp:fp.close()def seek(self, frame):"""Seeks to the given frame in this sequence file. If you seekbeyond the end of the sequence, the method raises an**EOFError** exception. When a sequence file is opened, thelibrary automatically seeks to frame 0.Note that in the current version of the library, most sequenceformats only allows you to seek to the next frame.See :py:meth:`~PIL.Image.Image.tell`.:param frame: Frame number, starting at 0.:exception EOFError: If the call attempts to seek beyond the endof the sequence."""# overridden by file handlersif frame != 0:raise EOFErrordef show(self, title=None, command=None):"""Displays this image. This method is mainly intended fordebugging purposes.On Unix platforms, this method saves the image to a temporaryPPM file, and calls either the **xv** utility or the **display**utility, depending on which one can be found.On macOS, this method saves the image to a temporary BMP file, andopens it with the native Preview application.On Windows, it saves the image to a temporary BMP file, and usesthe standard BMP display utility to show it (usually Paint).:param title: Optional title to use for the image window,where possible.:param command: command used to show the image"""_show(self, title=title, command=command)def split(self):"""Split this image into individual bands. This method returns atuple of individual image bands from an image. For example,splitting an "RGB" image creates three new images eachcontaining a copy of one of the original bands (red, green,blue).If you need only one band, :py:meth:`~PIL.Image.Image.getchannel`method can be more convenient and faster.:returns: A tuple containing bands."""self.load()if self.im.bands == 1:ims = [self.copy()]else:ims = map(self._new, self.im.split())return tuple(ims)def getchannel(self, channel):"""Returns an image containing a single channel of the source image.:param channel: What channel to return. Could be index(0 for "R" channel of "RGB") or channel name("A" for alpha channel of "RGBA").:returns: An image in "L" mode... versionadded:: 4.3.0"""self.load()if isStringType(channel):try:channel = self.getbands().index(channel)except ValueError:raise ValueError('The image has no channel "{}"'.format(channel))return self._new(self.im.getband(channel))def tell(self):"""Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.:returns: Frame number, starting with 0."""return 0def thumbnail(self, size, resample=BICUBIC):"""Make this image into a thumbnail. This method modifies theimage to contain a thumbnail version of itself, no larger thanthe given size. This method calculates an appropriate thumbnailsize to preserve the aspect of the image, calls the:py:meth:`~PIL.Image.Image.draft` method to configure the file reader(where applicable), and finally resizes the image.Note that this function modifies the :py:class:`~PIL.Image.Image`object in place. If you need to use the full resolution image as well,apply this method to a :py:meth:`~PIL.Image.Image.copy` of the originalimage.:param size: Requested size.:param resample: Optional resampling filter. This can be oneof :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,:py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.LANCZOS`.If omitted, it defaults to :py:attr:`PIL.Image.BICUBIC`.(was :py:attr:`PIL.Image.NEAREST` prior to version 2.5.0):returns: None"""# preserve aspect ratiox, y = self.sizeif x > size[0]:y = int(max(y * size[0] / x, 1))x = int(size[0])if y > size[1]:x = int(max(x * size[1] / y, 1))y = int(size[1])size = x, yif size == self.size:returnself.draft(None, size)im = self.resize(size, resample)self.im = im.imself.mode = im.modeself.size = sizeself.readonly = 0self.pyaccess = None# FIXME: the different transform methods need further explanation# instead of bloating the method docs, add a separate chapter.def transform(self, size, method, data=None, resample=NEAREST,fill=1, fillcolor=None):"""Transforms this image. This method creates a new image with thegiven size, and the same mode as the original, and copies datato the new image using the given transform.:param size: The output size.:param method: The transformation method. This is one of:py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),:py:attr:`PIL.Image.AFFINE` (affine transform),:py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),:py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or:py:attr:`PIL.Image.MESH` (map a number of source quadrilateralsin one operation).It may also be an :py:class:`~PIL.Image.ImageTransformHandler`object::class Example(Image.ImageTransformHandler):def transform(size, method, data, resample, fill=1):# Return resultIt may also be an object with a :py:meth:`~method.getdata` methodthat returns a tuple supplying new **method** and **data** values::class Example(object):def getdata(self):method = Image.EXTENTdata = (0, 0, 100, 100)return method, data:param data: Extra data to the transformation method.:param resample: Optional resampling filter. It can be one of:py:attr:`PIL.Image.NEAREST` (use nearest neighbour),:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2environment), or :py:attr:`PIL.Image.BICUBIC` (cubic splineinterpolation in a 4x4 environment). If omitted, or if the imagehas mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.:param fill: If **method** is an:py:class:`~PIL.Image.ImageTransformHandler` object, this is one ofthe arguments passed to it. Otherwise, it is unused.:param fillcolor: Optional fill color for the area outside the transformin the output image.:returns: An :py:class:`~PIL.Image.Image` object."""if self.mode == 'LA':return self.convert('La').transform(size, method, data, resample, fill, fillcolor).convert('LA')if self.mode == 'RGBA':return self.convert('RGBa').transform(size, method, data, resample, fill, fillcolor).convert('RGBA')if isinstance(method, ImageTransformHandler):return method.transform(size, self, resample=resample, fill=fill)if hasattr(method, "getdata"):# compatibility w. old-style transform objectsmethod, data = method.getdata()if data is None:raise ValueError("missing method data")im = new(self.mode, size, fillcolor)if method == MESH:# list of quadsfor box, quad in data:im.__transformer(box, self, QUAD, quad, resample,fillcolor is None)else:im.__transformer((0, 0)+size, self, method, data,resample, fillcolor is None)return imdef __transformer(self, box, image, method, data,resample=NEAREST, fill=1):w = box[2] - box[0]h = box[3] - box[1]if method == AFFINE:data = data[0:6]elif method == EXTENT:# convert extent to an affine transformx0, y0, x1, y1 = dataxs = float(x1 - x0) / wys = float(y1 - y0) / hmethod = AFFINEdata = (xs, 0, x0, 0, ys, y0)elif method == PERSPECTIVE:data = data[0:8]elif method == QUAD:# quadrilateral warp. data specifies the four corners# given as NW, SW, SE, and NE.nw = data[0:2]sw = data[2:4]se = data[4:6]ne = data[6:8]x0, y0 = nwAs = 1.0 / wAt = 1.0 / hdata = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,(se[0]-sw[0]-ne[0]+x0)*As*At,y0, (ne[1]-y0)*As, (sw[1]-y0)*At,(se[1]-sw[1]-ne[1]+y0)*As*At)else:raise ValueError("unknown transformation method")if resample not in (NEAREST, BILINEAR, BICUBIC):raise ValueError("unknown resampling filter")image.load()self.load()if image.mode in ("1", "P"):resample = NEARESTself.im.transform2(box, image.im, method, data, resample, fill)def transpose(self, method):"""Transpose image (flip or rotate in 90 degree steps):param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,:py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,:py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,:py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.:returns: Returns a flipped or rotated copy of this image."""self.load()return self._new(self.im.transpose(method))def effect_spread(self, distance):"""Randomly spread pixels in an image.:param distance: Distance to spread pixels."""self.load()return self._new(self.im.effect_spread(distance))def toqimage(self):"""Returns a QImage copy of this image"""from . import ImageQtif not ImageQt.qt_is_installed:raise ImportError("Qt bindings are not installed")return ImageQt.toqimage(self)def toqpixmap(self):"""Returns a QPixmap copy of this image"""from . import ImageQtif not ImageQt.qt_is_installed:raise ImportError("Qt bindings are not installed")return ImageQt.toqpixmap(self)# --------------------------------------------------------------------# Abstract handlers.class ImagePointHandler(object):# used as a mixin by point transforms (for use with im.point)passclass ImageTransformHandler(object):# used as a mixin by geometry transforms (for use with im.transform)pass# --------------------------------------------------------------------# Factories## Debuggingdef _wedge():"""Create greyscale wedge (for debugging only)"""return Image()._new(core.wedge("L"))def _check_size(size):"""Common check to enforce type and sanity check on size tuples:param size: Should be a 2 tuple of (width, height):returns: True, or raises a ValueError"""if not isinstance(size, (list, tuple)):raise ValueError("Size must be a tuple")if len(size) != 2:raise ValueError("Size must be a tuple of length 2")if size[0] < 0 or size[1] < 0:raise ValueError("Width and height must be >= 0")return Truedef new(mode, size, color=0):"""Creates a new image with the given mode and size.:param mode: The mode to use for the new image. See::ref:`concept-modes`.:param size: A 2-tuple, containing (width, height) in pixels.:param color: What color to use for the image. Default is black.If given, this should be a single integer or floating point valuefor single-band modes, and a tuple for multi-band modes (one valueper band). When creating RGB images, you can also use colorstrings as supported by the ImageColor module. If the color isNone, the image is not initialised.:returns: An :py:class:`~PIL.Image.Image` object."""_check_size(size)if color is None:# don't initializereturn Image()._new(core.new(mode, size))if isStringType(color):# css3-style specifierfrom . import ImageColorcolor = ImageColor.getcolor(color, mode)return Image()._new(core.fill(mode, size, color))def frombytes(mode, size, data, decoder_name="raw", *args):"""Creates a copy of an image memory from pixel data in a buffer.In its simplest form, this function takes three arguments(mode, size, and unpacked pixel data).You can also use any pixel decoder supported by PIL. For moreinformation on available decoders, see the section:ref:`Writing Your Own File Decoder <file-decoders>`.Note that this function decodes pixel data only, not entire images.If you have an entire image in a string, wrap it in a:py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to loadit.:param mode: The image mode. See: :ref:`concept-modes`.:param size: The image size.:param data: A byte buffer containing raw data for the given mode.:param decoder_name: What decoder to use.:param args: Additional parameters for the given decoder.:returns: An :py:class:`~PIL.Image.Image` object."""_check_size(size)# may pass tuple instead of argument listif len(args) == 1 and isinstance(args[0], tuple):args = args[0]if decoder_name == "raw" and args == ():args = modeim = new(mode, size)im.frombytes(data, decoder_name, args)return imdef fromstring(*args, **kw):raise NotImplementedError("fromstring() has been removed. " +"Please call frombytes() instead.")def frombuffer(mode, size, data, decoder_name="raw", *args):"""Creates an image memory referencing pixel data in a byte buffer.This function is similar to :py:func:`~PIL.Image.frombytes`, but uses datain the byte buffer, where possible. This means that changes to theoriginal buffer object are reflected in this image). Not all modes canshare memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".Note that this function decodes pixel data only, not entire images.If you have an entire image file in a string, wrap it in a**BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.In the current version, the default parameters used for the "raw" decoderdiffers from that used for :py:func:`~PIL.Image.frombytes`. This is abug, and will probably be fixed in a future release. The current releaseissues a warning if you do this; to disable the warning, you should providethe full set of parameters. See below for details.:param mode: The image mode. See: :ref:`concept-modes`.:param size: The image size.:param data: A bytes or other buffer object containing rawdata for the given mode.:param decoder_name: What decoder to use.:param args: Additional parameters for the given decoder. For thedefault encoder ("raw"), it's recommended that you provide thefull set of parameters::frombuffer(mode, size, data, "raw", mode, 0, 1):returns: An :py:class:`~PIL.Image.Image` object... versionadded:: 1.1.4"""_check_size(size)# may pass tuple instead of argument listif len(args) == 1 and isinstance(args[0], tuple):args = args[0]if decoder_name == "raw":if args == ():warnings.warn("the frombuffer defaults may change in a future release; ""for portability, change the call to read:\n"" frombuffer(mode, size, data, 'raw', mode, 0, 1)",RuntimeWarning, stacklevel=2)args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6if args[0] in _MAPMODES:im = new(mode, (1, 1))im = im._new(core.map_buffer(data, size, decoder_name, None, 0, args))im.readonly = 1return imreturn frombytes(mode, size, data, decoder_name, args)def fromarray(obj, mode=None):"""Creates an image memory from an object exporting the array interface(using the buffer protocol).If obj is not contiguous, then the tobytes method is calledand :py:func:`~PIL.Image.frombuffer` is used.:param obj: Object with array interface:param mode: Mode to use (will be determined from type if None)See: :ref:`concept-modes`.:returns: An image object... versionadded:: 1.1.6"""arr = obj.__array_interface__shape = arr['shape']ndim = len(shape)strides = arr.get('strides', None)if mode is None:try:typekey = (1, 1) + shape[2:], arr['typestr']mode, rawmode = _fromarray_typemap[typekey]except KeyError:# print(typekey)raise TypeError("Cannot handle this data type")else:rawmode = modeif mode in ["1", "L", "I", "P", "F"]:ndmax = 2elif mode == "RGB":ndmax = 3else:ndmax = 4if ndim > ndmax:raise ValueError("Too many dimensions: %d > %d." % (ndim, ndmax))size = shape[1], shape[0]if strides is not None:if hasattr(obj, 'tobytes'):obj = obj.tobytes()else:obj = obj.tostring()return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)def fromqimage(im):"""Creates an image instance from a QImage image"""from . import ImageQtif not ImageQt.qt_is_installed:raise ImportError("Qt bindings are not installed")return ImageQt.fromqimage(im)def fromqpixmap(im):"""Creates an image instance from a QPixmap image"""from . import ImageQtif not ImageQt.qt_is_installed:raise ImportError("Qt bindings are not installed")return ImageQt.fromqpixmap(im)_fromarray_typemap = {# (shape, typestr) => mode, rawmode# first two members of shape are set to one((1, 1), "|b1"): ("1", "1;8"),((1, 1), "|u1"): ("L", "L"),((1, 1), "|i1"): ("I", "I;8"),((1, 1), "<u2"): ("I", "I;16"),((1, 1), ">u2"): ("I", "I;16B"),((1, 1), "<i2"): ("I", "I;16S"),((1, 1), ">i2"): ("I", "I;16BS"),((1, 1), "<u4"): ("I", "I;32"),((1, 1), ">u4"): ("I", "I;32B"),((1, 1), "<i4"): ("I", "I;32S"),((1, 1), ">i4"): ("I", "I;32BS"),((1, 1), "<f4"): ("F", "F;32F"),((1, 1), ">f4"): ("F", "F;32BF"),((1, 1), "<f8"): ("F", "F;64F"),((1, 1), ">f8"): ("F", "F;64BF"),((1, 1, 2), "|u1"): ("LA", "LA"),((1, 1, 3), "|u1"): ("RGB", "RGB"),((1, 1, 4), "|u1"): ("RGBA", "RGBA"),}# shortcuts_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")def _decompression_bomb_check(size):if MAX_IMAGE_PIXELS is None:returnpixels = size[0] * size[1]if pixels > 2 * MAX_IMAGE_PIXELS:raise DecompressionBombError("Image size (%d pixels) exceeds limit of %d pixels, ""could be decompression bomb DOS attack." %(pixels, 2 * MAX_IMAGE_PIXELS))if pixels > MAX_IMAGE_PIXELS:warnings.warn("Image size (%d pixels) exceeds limit of %d pixels, ""could be decompression bomb DOS attack." %(pixels, MAX_IMAGE_PIXELS),DecompressionBombWarning)def open(fp, mode="r"):"""Opens and identifies the given image file.This is a lazy operation; this function identifies the file, butthe file remains open and the actual image data is not read fromthe file until you try to process the data (or call the:py:meth:`~PIL.Image.Image.load` method). See:py:func:`~PIL.Image.new`. See :ref:`file-handling`.:param fp: A filename (string), pathlib.Path object or a file object.The file object must implement :py:meth:`~file.read`,:py:meth:`~file.seek`, and :py:meth:`~file.tell` methods,and be opened in binary mode.:param mode: The mode. If given, this argument must be "r".:returns: An :py:class:`~PIL.Image.Image` object.:exception IOError: If the file cannot be found, or the image cannot beopened and identified."""if mode != "r":raise ValueError("bad mode %r" % mode)exclusive_fp = Falsefilename = ""if isPath(fp):filename = fpelif HAS_PATHLIB and isinstance(fp, Path):filename = str(fp.resolve())if filename:fp = builtins.open(filename, "rb")exclusive_fp = Truetry:fp.seek(0)except (AttributeError, io.UnsupportedOperation):fp = io.BytesIO(fp.read())exclusive_fp = Trueprefix = fp.read(16)preinit()def _open_core(fp, filename, prefix):for i in ID:try:factory, accept = OPEN[i]if not accept or accept(prefix):fp.seek(0)im = factory(fp, filename)_decompression_bomb_check(im.size)return imexcept (SyntaxError, IndexError, TypeError, struct.error):# Leave disabled by default, spams the logs with image# opening failures that are entirely expected.# logger.debug("", exc_info=True)continuereturn Noneim = _open_core(fp, filename, prefix)if im is None:if init():im = _open_core(fp, filename, prefix)if im:im._exclusive_fp = exclusive_fpreturn imif exclusive_fp:fp.close()raise IOError("cannot identify image file %r"% (filename if filename else fp))## Image processing.def alpha_composite(im1, im2):"""Alpha composite im2 over im1.:param im1: The first image. Must have mode RGBA.:param im2: The second image. Must have mode RGBA, and the same size asthe first image.:returns: An :py:class:`~PIL.Image.Image` object."""im1.load()im2.load()return im1._new(core.alpha_composite(im1.im, im2.im))def blend(im1, im2, alpha):"""Creates a new image by interpolating between two input images, usinga constant alpha.::out = image1 * (1.0 - alpha) + image2 * alpha:param im1: The first image.:param im2: The second image. Must have the same mode and size asthe first image.:param alpha: The interpolation alpha factor. If alpha is 0.0, acopy of the first image is returned. If alpha is 1.0, a copy ofthe second image is returned. There are no restrictions on thealpha value. If necessary, the result is clipped to fit intothe allowed output range.:returns: An :py:class:`~PIL.Image.Image` object."""im1.load()im2.load()return im1._new(core.blend(im1.im, im2.im, alpha))def composite(image1, image2, mask):"""Create composite image by blending images using a transparency mask.:param image1: The first image.:param image2: The second image. Must have the same mode andsize as the first image.:param mask: A mask image. This image can have mode"1", "L", or "RGBA", and must have the same size as theother two images."""image = image2.copy()image.paste(image1, None, mask)return imagedef eval(image, *args):"""Applies the function (which should take one argument) to each pixelin the given image. If the image has more than one band, the samefunction is applied to each band. Note that the function isevaluated once for each possible pixel value, so you cannot userandom components or other generators.:param image: The input image.:param function: A function object, taking one integer argument.:returns: An :py:class:`~PIL.Image.Image` object."""return image.point(args[0])def merge(mode, bands):"""Merge a set of single band images into a new multiband image.:param mode: The mode to use for the output image. See::ref:`concept-modes`.:param bands: A sequence containing one single-band image foreach band in the output image. All bands must have thesame size.:returns: An :py:class:`~PIL.Image.Image` object."""if getmodebands(mode) != len(bands) or "*" in mode:raise ValueError("wrong number of bands")for band in bands[1:]:if band.mode != getmodetype(mode):raise ValueError("mode mismatch")if band.size != bands[0].size:raise ValueError("size mismatch")for band in bands:band.load()return bands[0]._new(core.merge(mode, *[b.im for b in bands]))# --------------------------------------------------------------------# Plugin registrydef register_open(id, factory, accept=None):"""Register an image file plugin. This function should not be usedin application code.:param id: An image format identifier.:param factory: An image file factory method.:param accept: An optional function that can be used to quicklyreject images having another format."""id = id.upper()ID.append(id)OPEN[id] = factory, acceptdef register_mime(id, mimetype):"""Registers an image MIME type. This function should not be usedin application code.:param id: An image format identifier.:param mimetype: The image MIME type for this format."""MIME[id.upper()] = mimetypedef register_save(id, driver):"""Registers an image save function. This function should not beused in application code.:param id: An image format identifier.:param driver: A function to save images in this format."""SAVE[id.upper()] = driverdef register_save_all(id, driver):"""Registers an image function to save all the framesof a multiframe format. This function should not beused in application code.:param id: An image format identifier.:param driver: A function to save images in this format."""SAVE_ALL[id.upper()] = driverdef register_extension(id, extension):"""Registers an image extension. This function should not beused in application code.:param id: An image format identifier.:param extension: An extension used for this format."""EXTENSION[extension.lower()] = id.upper()def register_extensions(id, extensions):"""Registers image extensions. This function should not beused in application code.:param id: An image format identifier.:param extensions: A list of extensions used for this format."""for extension in extensions:register_extension(id, extension)def registered_extensions():"""Returns a dictionary containing all file extensions belongingto registered plugins"""if not EXTENSION:init()return EXTENSIONdef register_decoder(name, decoder):"""Registers an image decoder. This function should not beused in application code.:param name: The name of the decoder:param decoder: A callable(mode, args) that returns anImageFile.PyDecoder object.. versionadded:: 4.1.0"""DECODERS[name] = decoderdef register_encoder(name, encoder):"""Registers an image encoder. This function should not beused in application code.:param name: The name of the encoder:param encoder: A callable(mode, args) that returns anImageFile.PyEncoder object.. versionadded:: 4.1.0"""ENCODERS[name] = encoder# --------------------------------------------------------------------# Simple display support. User code may override this.def _show(image, **options):# override me, as necessary_showxv(image, **options)def _showxv(image, title=None, **options):from . import ImageShowImageShow.show(image, title, **options)# --------------------------------------------------------------------# Effectsdef effect_mandelbrot(size, extent, quality):"""Generate a Mandelbrot set covering the given extent.:param size: The requested size in pixels, as a 2-tuple:(width, height).:param extent: The extent to cover, as a 4-tuple:(x0, y0, x1, y2).:param quality: Quality."""return Image()._new(core.effect_mandelbrot(size, extent, quality))def effect_noise(size, sigma):"""Generate Gaussian noise centered around 128.:param size: The requested size in pixels, as a 2-tuple:(width, height).:param sigma: Standard deviation of noise."""return Image()._new(core.effect_noise(size, sigma))def linear_gradient(mode):"""Generate 256x256 linear gradient from black to white, top to bottom.:param mode: Input mode."""return Image()._new(core.linear_gradient(mode))def radial_gradient(mode):"""Generate 256x256 radial gradient from black to white, centre to edge.:param mode: Input mode."""return Image()._new(core.radial_gradient(mode))# --------------------------------------------------------------------# Resourcesdef _apply_env_variables(env=None):if env is None:env = os.environfor var_name, setter in [('PILLOW_ALIGNMENT', core.set_alignment),('PILLOW_BLOCK_SIZE', core.set_block_size),('PILLOW_BLOCKS_MAX', core.set_blocks_max),]:if var_name not in env:continuevar = env[var_name].lower()units = 1for postfix, mul in [('k', 1024), ('m', 1024*1024)]:if var.endswith(postfix):units = mulvar = var[:-len(postfix)]try:var = int(var) * unitsexcept ValueError:warnings.warn("{0} is not int".format(var_name))continuetry:setter(var)except ValueError as e:warnings.warn("{0}: {1}".format(var_name, e))_apply_env_variables()atexit.register(core.clear_cache)
123version https://git-lfs.github.com/spec/v1oid sha256:7f4ec99529bd2e7dfe3cf20cd7eca56dc869dbd1529ce3ee9c5c9c88b6723327size 6182123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283## The Python Imaging Library.# $Id$## standard channel operations## History:# 1996-03-24 fl Created# 1996-08-13 fl Added logical operations (for "1" images)# 2000-10-12 fl Added offset method (from Image.py)## Copyright (c) 1997-2000 by Secret Labs AB# Copyright (c) 1996-2000 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imagedef constant(image, value):"""Fill a channel with a given grey level.:rtype: :py:class:`~PIL.Image.Image`"""return Image.new("L", image.size, value)def duplicate(image):"""Copy a channel. Alias for :py:meth:`PIL.Image.Image.copy`.:rtype: :py:class:`~PIL.Image.Image`"""return image.copy()def invert(image):"""Invert an image (channel)... code-block:: pythonout = MAX - image:rtype: :py:class:`~PIL.Image.Image`"""image.load()return image._new(image.im.chop_invert())def lighter(image1, image2):"""Compares the two images, pixel by pixel, and returns a new image containingthe lighter values... code-block:: pythonout = max(image1, image2):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_lighter(image2.im))def darker(image1, image2):"""Compares the two images, pixel by pixel, and returns a new imagecontaining the darker values... code-block:: pythonout = min(image1, image2):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_darker(image2.im))def difference(image1, image2):"""Returns the absolute value of the pixel-by-pixel difference between the twoimages... code-block:: pythonout = abs(image1 - image2):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_difference(image2.im))def multiply(image1, image2):"""Superimposes two images on top of each other.If you multiply an image with a solid black image, the result is black. Ifyou multiply with a solid white image, the image is unaffected... code-block:: pythonout = image1 * image2 / MAX:rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_multiply(image2.im))def screen(image1, image2):"""Superimposes two inverted images on top of each other... code-block:: pythonout = MAX - ((MAX - image1) * (MAX - image2) / MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_screen(image2.im))def add(image1, image2, scale=1.0, offset=0):"""Adds two images, dividing the result by scale and adding theoffset. If omitted, scale defaults to 1.0, and offset to 0.0... code-block:: pythonout = ((image1 + image2) / scale + offset):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_add(image2.im, scale, offset))def subtract(image1, image2, scale=1.0, offset=0):"""Subtracts two images, dividing the result by scale and adding theoffset. If omitted, scale defaults to 1.0, and offset to 0.0... code-block:: pythonout = ((image1 - image2) / scale + offset):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_subtract(image2.im, scale, offset))def add_modulo(image1, image2):"""Add two images, without clipping the result... code-block:: pythonout = ((image1 + image2) % MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_add_modulo(image2.im))def subtract_modulo(image1, image2):"""Subtract two images, without clipping the result... code-block:: pythonout = ((image1 - image2) % MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_subtract_modulo(image2.im))def logical_and(image1, image2):"""Logical AND between two images... code-block:: pythonout = ((image1 and image2) % MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_and(image2.im))def logical_or(image1, image2):"""Logical OR between two images... code-block:: pythonout = ((image1 or image2) % MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_or(image2.im))def logical_xor(image1, image2):"""Logical XOR between two images... code-block:: pythonout = ((bool(image1) != bool(image2)) % MAX):rtype: :py:class:`~PIL.Image.Image`"""image1.load()image2.load()return image1._new(image1.im.chop_xor(image2.im))def blend(image1, image2, alpha):"""Blend images using constant transparency weight. Alias for:py:meth:`PIL.Image.Image.blend`.:rtype: :py:class:`~PIL.Image.Image`"""return Image.blend(image1, image2, alpha)def composite(image1, image2, mask):"""Create composite using transparency mask. Alias for:py:meth:`PIL.Image.Image.composite`.:rtype: :py:class:`~PIL.Image.Image`"""return Image.composite(image1, image2, mask)def offset(image, xoffset, yoffset=None):"""Returns a copy of the image where data has been offset by the givendistances. Data wraps around the edges. If **yoffset** is omitted, itis assumed to be equal to **xoffset**.:param xoffset: The horizontal distance.:param yoffset: The vertical distance. If omitted, bothdistances are set to the same value.:rtype: :py:class:`~PIL.Image.Image`"""if yoffset is None:yoffset = xoffsetimage.load()return image._new(image.im.offset(xoffset, yoffset))
123version https://git-lfs.github.com/spec/v1oid sha256:fe84e05360b09e42f2a75949231b4c752b987abf80b2b1169cf5cf3b6379b228size 36616123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955# The Python Imaging Library.# $Id$# Optional color management support, based on Kevin Cazabon's PyCMS# library.# History:# 2009-03-08 fl Added to PIL.# Copyright (C) 2002-2003 Kevin Cazabon# Copyright (c) 2009 by Fredrik Lundh# Copyright (c) 2013 by Eric Soroos# See the README file for information on usage and redistribution. See# below for the original description.from __future__ import print_functionimport sysfrom PIL import Imagetry:from PIL import _imagingcmsexcept ImportError as ex:# Allow error import for doc purposes, but error out when accessing# anything in core.from _util import deferred_error_imagingcms = deferred_error(ex)from PIL._util import isStringTypeDESCRIPTION = """pyCMSa Python / PIL interface to the littleCMS ICC Color Management SystemCopyright (C) 2002-2003 Kevin Cazabonkevin@cazabon.comhttp://www.cazabon.compyCMS home page: http://www.cazabon.com/pyCMSlittleCMS home page: http://www.littlecms.com(littleCMS is Copyright (C) 1998-2001 Marti Maria)Originally released under LGPL. Graciously donated to PIL inMarch 2009, for distribution under the standard PIL licenseThe pyCMS.py module provides a "clean" interface between Python/PIL andpyCMSdll, taking care of some of the more complex handling of the directpyCMSdll functions, as well as error-checking and making sure that allrelevant data is kept together.While it is possible to call pyCMSdll functions directly, it's not highlyrecommended.Version History:1.0.0 pil Oct 2013 Port to LCMS 2.0.1.0 pil mod March 10, 2009Renamed display profile to proof profile. The proofprofile is the profile of the device that is beingsimulated, not the profile of the device which isactually used to display/print the final simulation(that'd be the output profile) - also see LCMSAPI.txtinput colorspace -> using 'renderingIntent' -> proofcolorspace -> using 'proofRenderingIntent' -> outputcolorspaceAdded LCMS FLAGS support.Added FLAGS["SOFTPROOFING"] as default flag forbuildProofTransform (otherwise the proof profile/intentwould be ignored).0.1.0 pil March 2009 - added to PIL, as PIL.ImageCms0.0.2 alpha Jan 6, 2002Added try/except statements around type() checks ofpotential CObjects... Python won't let you use type()on them, and raises a TypeError (stupid, if you askme!)Added buildProofTransformFromOpenProfiles() function.Additional fixes in DLL, see DLL code for details.0.0.1 alpha first public release, Dec. 26, 2002Known to-do list with current version (of Python interface, not pyCMSdll):none"""VERSION = "1.0.0 pil"# --------------------------------------------------------------------.core = _imagingcms## intent/direction valuesINTENT_PERCEPTUAL = 0INTENT_RELATIVE_COLORIMETRIC = 1INTENT_SATURATION = 2INTENT_ABSOLUTE_COLORIMETRIC = 3DIRECTION_INPUT = 0DIRECTION_OUTPUT = 1DIRECTION_PROOF = 2## flagsFLAGS = {"MATRIXINPUT": 1,"MATRIXOUTPUT": 2,"MATRIXONLY": (1 | 2),"NOWHITEONWHITEFIXUP": 4, # Don't hot fix scum dot# Don't create prelinearization tables on precalculated transforms# (internal use):"NOPRELINEARIZATION": 16,"GUESSDEVICECLASS": 32, # Guess device class (for transform2devicelink)"NOTCACHE": 64, # Inhibit 1-pixel cache"NOTPRECALC": 256,"NULLTRANSFORM": 512, # Don't transform anyway"HIGHRESPRECALC": 1024, # Use more memory to give better accuracy"LOWRESPRECALC": 2048, # Use less memory to minimize resources"WHITEBLACKCOMPENSATION": 8192,"BLACKPOINTCOMPENSATION": 8192,"GAMUTCHECK": 4096, # Out of Gamut alarm"SOFTPROOFING": 16384, # Do softproofing"PRESERVEBLACK": 32768, # Black preservation"NODEFAULTRESOURCEDEF": 16777216, # CRD special"GRIDPOINTS": lambda n: ((n) & 0xFF) << 16 # Gridpoints}_MAX_FLAG = 0for flag in FLAGS.values():if isinstance(flag, int):_MAX_FLAG = _MAX_FLAG | flag# --------------------------------------------------------------------.# Experimental PIL-level API# --------------------------------------------------------------------.### Profile.class ImageCmsProfile(object):def __init__(self, profile):""":param profile: Either a string representing a filename,a file like object containing a profile or alow-level profile object"""if isStringType(profile):self._set(core.profile_open(profile), profile)elif hasattr(profile, "read"):self._set(core.profile_frombytes(profile.read()))elif isinstance(profile, _imagingcms.CmsProfile):self._set(profile)else:raise TypeError("Invalid type for Profile")def _set(self, profile, filename=None):self.profile = profileself.filename = filenameif profile:self.product_name = None # profile.product_nameself.product_info = None # profile.product_infoelse:self.product_name = Noneself.product_info = Nonedef tobytes(self):"""Returns the profile in a format suitable for embedding insaved images.:returns: a bytes object containing the ICC profile."""return core.profile_tobytes(self.profile)class ImageCmsTransform(Image.ImagePointHandler):"""Transform. This can be used with the procedural API, or with the standardImage.point() method.Will return the output profile in the output.info['icc_profile']."""def __init__(self, input, output, input_mode, output_mode,intent=INTENT_PERCEPTUAL, proof=None,proof_intent=INTENT_ABSOLUTE_COLORIMETRIC, flags=0):if proof is None:self.transform = core.buildTransform(input.profile, output.profile,input_mode, output_mode,intent,flags)else:self.transform = core.buildProofTransform(input.profile, output.profile, proof.profile,input_mode, output_mode,intent, proof_intent,flags)# Note: inputMode and outputMode are for pyCMS compatibility onlyself.input_mode = self.inputMode = input_modeself.output_mode = self.outputMode = output_modeself.output_profile = outputdef point(self, im):return self.apply(im)def apply(self, im, imOut=None):im.load()if imOut is None:imOut = Image.new(self.output_mode, im.size, None)self.transform.apply(im.im.id, imOut.im.id)imOut.info['icc_profile'] = self.output_profile.tobytes()return imOutdef apply_in_place(self, im):im.load()if im.mode != self.output_mode:raise ValueError("mode mismatch") # wrong output modeself.transform.apply(im.im.id, im.im.id)im.info['icc_profile'] = self.output_profile.tobytes()return imdef get_display_profile(handle=None):""" (experimental) Fetches the profile for the current display device.:returns: None if the profile is not known."""if sys.platform == "win32":from PIL import ImageWinif isinstance(handle, ImageWin.HDC):profile = core.get_display_profile_win32(handle, 1)else:profile = core.get_display_profile_win32(handle or 0)else:try:get = _imagingcms.get_display_profileexcept AttributeError:return Noneelse:profile = get()return ImageCmsProfile(profile)# --------------------------------------------------------------------.# pyCMS compatible layer# --------------------------------------------------------------------.class PyCMSError(Exception):""" (pyCMS) Exception class.This is used for all errors in the pyCMS API. """passdef profileToProfile(im, inputProfile, outputProfile, renderingIntent=INTENT_PERCEPTUAL,outputMode=None, inPlace=0, flags=0):"""(pyCMS) Applies an ICC transformation to a given image, mapping frominputProfile to outputProfile.If the input or output profiles specified are not valid filenames, aPyCMSError will be raised. If inPlace == TRUE and outputMode != im.mode,a PyCMSError will be raised. If an error occurs during application ofthe profiles, a PyCMSError will be raised. If outputMode is not a modesupported by the outputProfile (or by pyCMS), a PyCMSError will beraised.This function applies an ICC transformation to im from inputProfile'scolor space to outputProfile's color space using the specified renderingintent to decide how to handle out-of-gamut colors.OutputMode can be used to specify that a color mode conversion is tobe done using these profiles, but the specified profiles must be ableto handle that mode. I.e., if converting im from RGB to CMYK usingprofiles, the input profile must handle RGB data, and the outputprofile must handle CMYK data.:param im: An open PIL image object (i.e. Image.new(...) orImage.open(...), etc.):param inputProfile: String, as a valid filename path to the ICC inputprofile you wish to use for this image, or a profile object:param outputProfile: String, as a valid filename path to the ICC outputprofile you wish to use for this image, or a profile object:param renderingIntent: Integer (0-3) specifying the rendering intent youwish to use for the transformINTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:param outputMode: A valid PIL mode for the output image (i.e. "RGB","CMYK", etc.). Note: if rendering the image "inPlace", outputModeMUST be the same mode as the input, or omitted completely. Ifomitted, the outputMode will be the same as the mode of the inputimage (im.mode):param inPlace: Boolean (1 = True, None or 0 = False). If True, theoriginal image is modified in-place, and None is returned. If False(default), a new Image object is returned with the transform applied.:param flags: Integer (0-...) specifying additional flags:returns: Either None or a new PIL image object, depending on value ofinPlace:exception PyCMSError:"""if outputMode is None:outputMode = im.modeif not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):raise PyCMSError("renderingIntent must be an integer between 0 and 3")if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)try:if not isinstance(inputProfile, ImageCmsProfile):inputProfile = ImageCmsProfile(inputProfile)if not isinstance(outputProfile, ImageCmsProfile):outputProfile = ImageCmsProfile(outputProfile)transform = ImageCmsTransform(inputProfile, outputProfile, im.mode, outputMode,renderingIntent, flags=flags)if inPlace:transform.apply_in_place(im)imOut = Noneelse:imOut = transform.apply(im)except (IOError, TypeError, ValueError) as v:raise PyCMSError(v)return imOutdef getOpenProfile(profileFilename):"""(pyCMS) Opens an ICC profile file.The PyCMSProfile object can be passed back into pyCMS for use in creatingtransforms and such (as in ImageCms.buildTransformFromOpenProfiles()).If profileFilename is not a valid filename for an ICC profile, a PyCMSErrorwill be raised.:param profileFilename: String, as a valid filename path to the ICC profileyou wish to open, or a file-like object.:returns: A CmsProfile class object.:exception PyCMSError:"""try:return ImageCmsProfile(profileFilename)except (IOError, TypeError, ValueError) as v:raise PyCMSError(v)def buildTransform(inputProfile, outputProfile, inMode, outMode,renderingIntent=INTENT_PERCEPTUAL, flags=0):"""(pyCMS) Builds an ICC transform mapping from the inputProfile to theoutputProfile. Use applyTransform to apply the transform to a givenimage.If the input or output profiles specified are not valid filenames, aPyCMSError will be raised. If an error occurs during creation of thetransform, a PyCMSError will be raised.If inMode or outMode are not a mode supported by the outputProfile (orby pyCMS), a PyCMSError will be raised.This function builds and returns an ICC transform from the inputProfileto the outputProfile using the renderingIntent to determine what to dowith out-of-gamut colors. It will ONLY work for converting images thatare in inMode to images that are in outMode color format (PIL mode,i.e. "RGB", "RGBA", "CMYK", etc.).Building the transform is a fair part of the overhead inImageCms.profileToProfile(), so if you're planning on converting multipleimages using the same input/output settings, this can save you time.Once you have a transform object, it can be used withImageCms.applyProfile() to convert images without the need to re-computethe lookup table for the transform.The reason pyCMS returns a class object rather than a handle directlyto the transform is that it needs to keep track of the PIL input/outputmodes that the transform is meant for. These attributes are stored inthe "inMode" and "outMode" attributes of the object (which can bemanually overridden if you really want to, but I don't know of anytime that would be of use, or would even work).:param inputProfile: String, as a valid filename path to the ICC inputprofile you wish to use for this transform, or a profile object:param outputProfile: String, as a valid filename path to the ICC outputprofile you wish to use for this transform, or a profile object:param inMode: String, as a valid PIL mode that the appropriate profilealso supports (i.e. "RGB", "RGBA", "CMYK", etc.):param outMode: String, as a valid PIL mode that the appropriate profilealso supports (i.e. "RGB", "RGBA", "CMYK", etc.):param renderingIntent: Integer (0-3) specifying the rendering intent youwish to use for the transformINTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:param flags: Integer (0-...) specifying additional flags:returns: A CmsTransform class object.:exception PyCMSError:"""if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):raise PyCMSError("renderingIntent must be an integer between 0 and 3")if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)try:if not isinstance(inputProfile, ImageCmsProfile):inputProfile = ImageCmsProfile(inputProfile)if not isinstance(outputProfile, ImageCmsProfile):outputProfile = ImageCmsProfile(outputProfile)return ImageCmsTransform(inputProfile, outputProfile, inMode, outMode,renderingIntent, flags=flags)except (IOError, TypeError, ValueError) as v:raise PyCMSError(v)def buildProofTransform(inputProfile, outputProfile, proofProfile, inMode, outMode,renderingIntent=INTENT_PERCEPTUAL,proofRenderingIntent=INTENT_ABSOLUTE_COLORIMETRIC,flags=FLAGS["SOFTPROOFING"]):"""(pyCMS) Builds an ICC transform mapping from the inputProfile to theoutputProfile, but tries to simulate the result that would beobtained on the proofProfile device.If the input, output, or proof profiles specified are not validfilenames, a PyCMSError will be raised.If an error occurs during creation of the transform, a PyCMSError willbe raised.If inMode or outMode are not a mode supported by the outputProfile(or by pyCMS), a PyCMSError will be raised.This function builds and returns an ICC transform from the inputProfileto the outputProfile, but tries to simulate the result that would beobtained on the proofProfile device using renderingIntent andproofRenderingIntent to determine what to do with out-of-gamutcolors. This is known as "soft-proofing". It will ONLY work forconverting images that are in inMode to images that are in outModecolor format (PIL mode, i.e. "RGB", "RGBA", "CMYK", etc.).Usage of the resulting transform object is exactly the same as withImageCms.buildTransform().Proof profiling is generally used when using an output device to get agood idea of what the final printed/displayed image would look like onthe proofProfile device when it's quicker and easier to use theoutput device for judging color. Generally, this means that theoutput device is a monitor, or a dye-sub printer (etc.), and the simulateddevice is something more expensive, complicated, or time consuming(making it difficult to make a real print for color judgement purposes).Soft-proofing basically functions by adjusting the colors on theoutput device to match the colors of the device being simulated. However,when the simulated device has a much wider gamut than the outputdevice, you may obtain marginal results.:param inputProfile: String, as a valid filename path to the ICC inputprofile you wish to use for this transform, or a profile object:param outputProfile: String, as a valid filename path to the ICC output(monitor, usually) profile you wish to use for this transform, or aprofile object:param proofProfile: String, as a valid filename path to the ICC proofprofile you wish to use for this transform, or a profile object:param inMode: String, as a valid PIL mode that the appropriate profilealso supports (i.e. "RGB", "RGBA", "CMYK", etc.):param outMode: String, as a valid PIL mode that the appropriate profilealso supports (i.e. "RGB", "RGBA", "CMYK", etc.):param renderingIntent: Integer (0-3) specifying the rendering intent youwish to use for the input->proof (simulated) transformINTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:param proofRenderingIntent: Integer (0-3) specifying the rendering intent youwish to use for proof->output transformINTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:param flags: Integer (0-...) specifying additional flags:returns: A CmsTransform class object.:exception PyCMSError:"""if not isinstance(renderingIntent, int) or not (0 <= renderingIntent <= 3):raise PyCMSError("renderingIntent must be an integer between 0 and 3")if not isinstance(flags, int) or not (0 <= flags <= _MAX_FLAG):raise PyCMSError("flags must be an integer between 0 and %s" + _MAX_FLAG)try:if not isinstance(inputProfile, ImageCmsProfile):inputProfile = ImageCmsProfile(inputProfile)if not isinstance(outputProfile, ImageCmsProfile):outputProfile = ImageCmsProfile(outputProfile)if not isinstance(proofProfile, ImageCmsProfile):proofProfile = ImageCmsProfile(proofProfile)return ImageCmsTransform(inputProfile, outputProfile, inMode, outMode, renderingIntent,proofProfile, proofRenderingIntent, flags)except (IOError, TypeError, ValueError) as v:raise PyCMSError(v)buildTransformFromOpenProfiles = buildTransformbuildProofTransformFromOpenProfiles = buildProofTransformdef applyTransform(im, transform, inPlace=0):"""(pyCMS) Applies a transform to a given image.If im.mode != transform.inMode, a PyCMSError is raised.If inPlace == TRUE and transform.inMode != transform.outMode, aPyCMSError is raised.If im.mode, transfer.inMode, or transfer.outMode is not supported bypyCMSdll or the profiles you used for the transform, a PyCMSError israised.If an error occurs while the transform is being applied, a PyCMSErroris raised.This function applies a pre-calculated transform (fromImageCms.buildTransform() or ImageCms.buildTransformFromOpenProfiles())to an image. The transform can be used for multiple images, savingconsiderable calculation time if doing the same conversion multiple times.If you want to modify im in-place instead of receiving a new image asthe return value, set inPlace to TRUE. This can only be done iftransform.inMode and transform.outMode are the same, because we can'tchange the mode in-place (the buffer sizes for some modes aredifferent). The default behavior is to return a new Image object ofthe same dimensions in mode transform.outMode.:param im: A PIL Image object, and im.mode must be the same as the inModesupported by the transform.:param transform: A valid CmsTransform class object:param inPlace: Bool (1 == True, 0 or None == False). If True, im ismodified in place and None is returned, if False, a new Image objectwith the transform applied is returned (and im is not changed). Thedefault is False.:returns: Either None, or a new PIL Image object, depending on the value ofinPlace. The profile will be returned in the image'sinfo['icc_profile'].:exception PyCMSError:"""try:if inPlace:transform.apply_in_place(im)imOut = Noneelse:imOut = transform.apply(im)except (TypeError, ValueError) as v:raise PyCMSError(v)return imOutdef createProfile(colorSpace, colorTemp=-1):"""(pyCMS) Creates a profile.If colorSpace not in ["LAB", "XYZ", "sRGB"], a PyCMSError is raisedIf using LAB and colorTemp != a positive integer, a PyCMSError is raised.If an error occurs while creating the profile, a PyCMSError is raised.Use this function to create common profiles on-the-fly instead ofhaving to supply a profile on disk and knowing the path to it. Itreturns a normal CmsProfile object that can be passed toImageCms.buildTransformFromOpenProfiles() to create a transform to applyto images.:param colorSpace: String, the color space of the profile you wish tocreate.Currently only "LAB", "XYZ", and "sRGB" are supported.:param colorTemp: Positive integer for the white point for the profile, indegrees Kelvin (i.e. 5000, 6500, 9600, etc.). The default is for D50illuminant if omitted (5000k). colorTemp is ONLY applied to LABprofiles, and is ignored for XYZ and sRGB.:returns: A CmsProfile class object:exception PyCMSError:"""if colorSpace not in ["LAB", "XYZ", "sRGB"]:raise PyCMSError("Color space not supported for on-the-fly profile creation (%s)"% colorSpace)if colorSpace == "LAB":try:colorTemp = float(colorTemp)except:raise PyCMSError("Color temperature must be numeric, \"%s\" not valid"% colorTemp)try:return core.createProfile(colorSpace, colorTemp)except (TypeError, ValueError) as v:raise PyCMSError(v)def getProfileName(profile):"""(pyCMS) Gets the internal product name for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised If an error occurs while trying to obtain thename tag, a PyCMSError is raised.Use this function to obtain the INTERNAL name of the profile (storedin an ICC tag in the profile itself), usually the one used when theprofile was originally created. Sometimes this tag also containsadditional information supplied by the creator.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal name of the profile as storedin an ICC tag.:exception PyCMSError:"""try:# add an extra newline to preserve pyCMS compatibilityif not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)# do it in python, not c.# // name was "%s - %s" (model, manufacturer) || Description ,# // but if the Model and Manufacturer were the same or the model# // was long, Just the model, in 1.xmodel = profile.profile.product_modelmanufacturer = profile.profile.product_manufacturerif not (model or manufacturer):return profile.profile.product_description + "\n"if not manufacturer or len(model) > 30:return model + "\n"return "%s - %s\n" % (model, manufacturer)except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getProfileInfo(profile):"""(pyCMS) Gets the internal product information for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the info tag, a PyCMSErroris raisedUse this function to obtain the information stored in the profile'sinfo tag. This often contains details about the profile, and how itwas created, as supplied by the creator.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal profile information stored inan ICC tag.:exception PyCMSError:"""try:if not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)# add an extra newline to preserve pyCMS compatibility# Python, not C. the white point bits weren't working well,# so skipping.# // info was description \r\n\r\n copyright \r\n\r\n K007 tag \r\n\r\n whitepointdescription = profile.profile.product_descriptioncpright = profile.profile.product_copyrightarr = []for elt in (description, cpright):if elt:arr.append(elt)return "\r\n\r\n".join(arr) + "\r\n\r\n"except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getProfileCopyright(profile):"""(pyCMS) Gets the copyright for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the copyright tag, a PyCMSErroris raisedUse this function to obtain the information stored in the profile'scopyright tag.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal profile information stored inan ICC tag.:exception PyCMSError:"""try:# add an extra newline to preserve pyCMS compatibilityif not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)return profile.profile.product_copyright + "\n"except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getProfileManufacturer(profile):"""(pyCMS) Gets the manufacturer for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the manufacturer tag, aPyCMSError is raisedUse this function to obtain the information stored in the profile'smanufacturer tag.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal profile information stored inan ICC tag.:exception PyCMSError:"""try:# add an extra newline to preserve pyCMS compatibilityif not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)return profile.profile.product_manufacturer + "\n"except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getProfileModel(profile):"""(pyCMS) Gets the model for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the model tag, a PyCMSErroris raisedUse this function to obtain the information stored in the profile'smodel tag.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal profile information stored inan ICC tag.:exception PyCMSError:"""try:# add an extra newline to preserve pyCMS compatibilityif not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)return profile.profile.product_model + "\n"except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getProfileDescription(profile):"""(pyCMS) Gets the description for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the description tag, a PyCMSErroris raisedUse this function to obtain the information stored in the profile'sdescription tag.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: A string containing the internal profile information stored in anICC tag.:exception PyCMSError:"""try:# add an extra newline to preserve pyCMS compatibilityif not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)return profile.profile.product_description + "\n"except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def getDefaultIntent(profile):"""(pyCMS) Gets the default intent name for the given profile.If profile isn't a valid CmsProfile object or filename to a profile,a PyCMSError is raised.If an error occurs while trying to obtain the default intent, aPyCMSError is raised.Use this function to determine the default (and usually best optimized)rendering intent for this profile. Most profiles support multiplerendering intents, but are intended mostly for one type of conversion.If you wish to use a different intent than returned, useImageCms.isIntentSupported() to verify it will work first.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:returns: Integer 0-3 specifying the default rendering intent for thisprofile.INTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:exception PyCMSError:"""try:if not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)return profile.profile.rendering_intentexcept (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def isIntentSupported(profile, intent, direction):"""(pyCMS) Checks if a given intent is supported.Use this function to verify that you can use your desiredrenderingIntent with profile, and that profile can be used for theinput/output/proof profile as you desire.Some profiles are created specifically for one "direction", can cannotbe used for others. Some profiles can only be used for certainrendering intents... so it's best to either verify this before tryingto create a transform with them (using this function), or catch thepotential PyCMSError that will occur if they don't support the modesyou select.:param profile: EITHER a valid CmsProfile object, OR a string of thefilename of an ICC profile.:param intent: Integer (0-3) specifying the rendering intent you wish touse with this profileINTENT_PERCEPTUAL = 0 (DEFAULT) (ImageCms.INTENT_PERCEPTUAL)INTENT_RELATIVE_COLORIMETRIC = 1 (ImageCms.INTENT_RELATIVE_COLORIMETRIC)INTENT_SATURATION = 2 (ImageCms.INTENT_SATURATION)INTENT_ABSOLUTE_COLORIMETRIC = 3 (ImageCms.INTENT_ABSOLUTE_COLORIMETRIC)see the pyCMS documentation for details on rendering intents and whatthey do.:param direction: Integer specifying if the profile is to be used for input,output, or proofINPUT = 0 (or use ImageCms.DIRECTION_INPUT)OUTPUT = 1 (or use ImageCms.DIRECTION_OUTPUT)PROOF = 2 (or use ImageCms.DIRECTION_PROOF):returns: 1 if the intent/direction are supported, -1 if they are not.:exception PyCMSError:"""try:if not isinstance(profile, ImageCmsProfile):profile = ImageCmsProfile(profile)# FIXME: I get different results for the same data w. different# compilers. Bug in LittleCMS or in the binding?if profile.profile.is_intent_supported(intent, direction):return 1else:return -1except (AttributeError, IOError, TypeError, ValueError) as v:raise PyCMSError(v)def versions():"""(pyCMS) Fetches versions."""return (VERSION, core.littlecms_version,sys.version.split()[0], Image.VERSION)
123version https://git-lfs.github.com/spec/v1oid sha256:72d059a5aefc1fc92ac4cf24aa94f5d9cd2dc340fcd76616cbe2ad465fa6ba90size 8703123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309## The Python Imaging Library# $Id$## map CSS3-style colour description strings to RGB## History:# 2002-10-24 fl Added support for CSS-style color strings# 2002-12-15 fl Added RGBA support# 2004-03-27 fl Fixed remaining int() problems for Python 1.5.2# 2004-07-19 fl Fixed gray/grey spelling issues# 2009-03-05 fl Fixed rounding error in grayscale calculation## Copyright (c) 2002-2004 by Secret Labs AB# Copyright (c) 2002-2004 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imageimport redef getrgb(color):"""Convert a color string to an RGB tuple. If the string cannot be parsed,this function raises a :py:exc:`ValueError` exception... versionadded:: 1.1.4:param color: A color string:return: ``(red, green, blue[, alpha])``"""color = color.lower()rgb = colormap.get(color, None)if rgb:if isinstance(rgb, tuple):return rgbcolormap[color] = rgb = getrgb(rgb)return rgb# check for known string formatsif re.match('#[a-f0-9]{3}$', color):return (int(color[1]*2, 16),int(color[2]*2, 16),int(color[3]*2, 16),)if re.match('#[a-f0-9]{4}$', color):return (int(color[1]*2, 16),int(color[2]*2, 16),int(color[3]*2, 16),int(color[4]*2, 16),)if re.match('#[a-f0-9]{6}$', color):return (int(color[1:3], 16),int(color[3:5], 16),int(color[5:7], 16),)if re.match('#[a-f0-9]{8}$', color):return (int(color[1:3], 16),int(color[3:5], 16),int(color[5:7], 16),int(color[7:9], 16),)m = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color)if m:return (int(m.group(1)),int(m.group(2)),int(m.group(3)))m = re.match(r"rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)$", color)if m:return (int((int(m.group(1)) * 255) / 100.0 + 0.5),int((int(m.group(2)) * 255) / 100.0 + 0.5),int((int(m.group(3)) * 255) / 100.0 + 0.5))m = re.match(r"hsl\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color)if m:from colorsys import hls_to_rgbrgb = hls_to_rgb(float(m.group(1)) / 360.0,float(m.group(3)) / 100.0,float(m.group(2)) / 100.0,)return (int(rgb[0] * 255 + 0.5),int(rgb[1] * 255 + 0.5),int(rgb[2] * 255 + 0.5))m = re.match(r"hs[bv]\(\s*(\d+\.?\d*)\s*,\s*(\d+\.?\d*)%\s*,\s*(\d+\.?\d*)%\s*\)$", color)if m:from colorsys import hsv_to_rgbrgb = hsv_to_rgb(float(m.group(1)) / 360.0,float(m.group(2)) / 100.0,float(m.group(3)) / 100.0,)return (int(rgb[0] * 255 + 0.5),int(rgb[1] * 255 + 0.5),int(rgb[2] * 255 + 0.5))m = re.match(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$",color)if m:return (int(m.group(1)),int(m.group(2)),int(m.group(3)),int(m.group(4)))raise ValueError("unknown color specifier: %r" % color)def getcolor(color, mode):"""Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to agreyscale value if the mode is not color or a palette image. If the stringcannot be parsed, this function raises a :py:exc:`ValueError` exception... versionadded:: 1.1.4:param color: A color string:return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])``"""# same as getrgb, but converts the result to the given modecolor, alpha = getrgb(color), 255if len(color) == 4:color, alpha = color[0:3], color[3]if Image.getmodebase(mode) == "L":r, g, b = colorcolor = (r*299 + g*587 + b*114)//1000if mode[-1] == 'A':return (color, alpha)else:if mode[-1] == 'A':return color + (alpha,)return colorcolormap = {# X11 colour table from https://drafts.csswg.org/css-color-4/, with# gray/grey spelling issues fixed. This is a superset of HTML 4.0# colour names used in CSS 1."aliceblue": "#f0f8ff","antiquewhite": "#faebd7","aqua": "#00ffff","aquamarine": "#7fffd4","azure": "#f0ffff","beige": "#f5f5dc","bisque": "#ffe4c4","black": "#000000","blanchedalmond": "#ffebcd","blue": "#0000ff","blueviolet": "#8a2be2","brown": "#a52a2a","burlywood": "#deb887","cadetblue": "#5f9ea0","chartreuse": "#7fff00","chocolate": "#d2691e","coral": "#ff7f50","cornflowerblue": "#6495ed","cornsilk": "#fff8dc","crimson": "#dc143c","cyan": "#00ffff","darkblue": "#00008b","darkcyan": "#008b8b","darkgoldenrod": "#b8860b","darkgray": "#a9a9a9","darkgrey": "#a9a9a9","darkgreen": "#006400","darkkhaki": "#bdb76b","darkmagenta": "#8b008b","darkolivegreen": "#556b2f","darkorange": "#ff8c00","darkorchid": "#9932cc","darkred": "#8b0000","darksalmon": "#e9967a","darkseagreen": "#8fbc8f","darkslateblue": "#483d8b","darkslategray": "#2f4f4f","darkslategrey": "#2f4f4f","darkturquoise": "#00ced1","darkviolet": "#9400d3","deeppink": "#ff1493","deepskyblue": "#00bfff","dimgray": "#696969","dimgrey": "#696969","dodgerblue": "#1e90ff","firebrick": "#b22222","floralwhite": "#fffaf0","forestgreen": "#228b22","fuchsia": "#ff00ff","gainsboro": "#dcdcdc","ghostwhite": "#f8f8ff","gold": "#ffd700","goldenrod": "#daa520","gray": "#808080","grey": "#808080","green": "#008000","greenyellow": "#adff2f","honeydew": "#f0fff0","hotpink": "#ff69b4","indianred": "#cd5c5c","indigo": "#4b0082","ivory": "#fffff0","khaki": "#f0e68c","lavender": "#e6e6fa","lavenderblush": "#fff0f5","lawngreen": "#7cfc00","lemonchiffon": "#fffacd","lightblue": "#add8e6","lightcoral": "#f08080","lightcyan": "#e0ffff","lightgoldenrodyellow": "#fafad2","lightgreen": "#90ee90","lightgray": "#d3d3d3","lightgrey": "#d3d3d3","lightpink": "#ffb6c1","lightsalmon": "#ffa07a","lightseagreen": "#20b2aa","lightskyblue": "#87cefa","lightslategray": "#778899","lightslategrey": "#778899","lightsteelblue": "#b0c4de","lightyellow": "#ffffe0","lime": "#00ff00","limegreen": "#32cd32","linen": "#faf0e6","magenta": "#ff00ff","maroon": "#800000","mediumaquamarine": "#66cdaa","mediumblue": "#0000cd","mediumorchid": "#ba55d3","mediumpurple": "#9370db","mediumseagreen": "#3cb371","mediumslateblue": "#7b68ee","mediumspringgreen": "#00fa9a","mediumturquoise": "#48d1cc","mediumvioletred": "#c71585","midnightblue": "#191970","mintcream": "#f5fffa","mistyrose": "#ffe4e1","moccasin": "#ffe4b5","navajowhite": "#ffdead","navy": "#000080","oldlace": "#fdf5e6","olive": "#808000","olivedrab": "#6b8e23","orange": "#ffa500","orangered": "#ff4500","orchid": "#da70d6","palegoldenrod": "#eee8aa","palegreen": "#98fb98","paleturquoise": "#afeeee","palevioletred": "#db7093","papayawhip": "#ffefd5","peachpuff": "#ffdab9","peru": "#cd853f","pink": "#ffc0cb","plum": "#dda0dd","powderblue": "#b0e0e6","purple": "#800080","rebeccapurple": "#663399","red": "#ff0000","rosybrown": "#bc8f8f","royalblue": "#4169e1","saddlebrown": "#8b4513","salmon": "#fa8072","sandybrown": "#f4a460","seagreen": "#2e8b57","seashell": "#fff5ee","sienna": "#a0522d","silver": "#c0c0c0","skyblue": "#87ceeb","slateblue": "#6a5acd","slategray": "#708090","slategrey": "#708090","snow": "#fffafa","springgreen": "#00ff7f","steelblue": "#4682b4","tan": "#d2b48c","teal": "#008080","thistle": "#d8bfd8","tomato": "#ff6347","turquoise": "#40e0d0","violet": "#ee82ee","wheat": "#f5deb3","white": "#ffffff","whitesmoke": "#f5f5f5","yellow": "#ffff00","yellowgreen": "#9acd32",}
123version https://git-lfs.github.com/spec/v1oid sha256:9ee19e92841e2e4e8086234c505e0fdcbc19464fc71d54c31fce846317992e27size 13689123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387## The Python Imaging Library# $Id$## drawing interface operations## History:# 1996-04-13 fl Created (experimental)# 1996-08-07 fl Filled polygons, ellipses.# 1996-08-13 fl Added text support# 1998-06-28 fl Handle I and F images# 1998-12-29 fl Added arc; use arc primitive to draw ellipses# 1999-01-10 fl Added shape stuff (experimental)# 1999-02-06 fl Added bitmap support# 1999-02-11 fl Changed all primitives to take options# 1999-02-20 fl Fixed backwards compatibility# 2000-10-12 fl Copy on write, when necessary# 2001-02-18 fl Use default ink for bitmap/text also in fill mode# 2002-10-24 fl Added support for CSS-style color strings# 2002-12-10 fl Added experimental support for RGBA-on-RGB drawing# 2002-12-11 fl Refactored low-level drawing API (work in progress)# 2004-08-26 fl Made Draw() a factory function, added getdraw() support# 2004-09-04 fl Added width support to line primitive# 2004-09-10 fl Added font mode handling# 2006-06-19 fl Added font bearing support (getmask2)## Copyright (c) 1997-2006 by Secret Labs AB# Copyright (c) 1996-2006 by Fredrik Lundh## See the README file for information on usage and redistribution.#import numbersfrom . import Image, ImageColorfrom ._util import isStringType"""A simple 2D drawing interface for PIL images.<p>Application code should use the <b>Draw</b> factory, instead ofdirectly."""class ImageDraw(object):def __init__(self, im, mode=None):"""Create a drawing instance.:param im: The image to draw in.:param mode: Optional mode to use for color values. For RGBimages, this argument can be RGB or RGBA (to blend thedrawing into the image). For all other modes, this argumentmust be the same as the image mode. If omitted, the modedefaults to the mode of the image."""im.load()if im.readonly:im._copy() # make it writeableblend = 0if mode is None:mode = im.modeif mode != im.mode:if mode == "RGBA" and im.mode == "RGB":blend = 1else:raise ValueError("mode mismatch")if mode == "P":self.palette = im.paletteelse:self.palette = Noneself.im = im.imself.draw = Image.core.draw(self.im, blend)self.mode = modeif mode in ("I", "F"):self.ink = self.draw.draw_ink(1, mode)else:self.ink = self.draw.draw_ink(-1, mode)if mode in ("1", "P", "I", "F"):# FIXME: fix Fill2 to properly support matte for I+F imagesself.fontmode = "1"else:self.fontmode = "L" # aliasing is okay for other modesself.fill = 0self.font = Nonedef getfont(self):"""Get the current default font.:returns: An image font."""if not self.font:# FIXME: should add a font repositoryfrom . import ImageFontself.font = ImageFont.load_default()return self.fontdef _getink(self, ink, fill=None):if ink is None and fill is None:if self.fill:fill = self.inkelse:ink = self.inkelse:if ink is not None:if isStringType(ink):ink = ImageColor.getcolor(ink, self.mode)if self.palette and not isinstance(ink, numbers.Number):ink = self.palette.getcolor(ink)ink = self.draw.draw_ink(ink, self.mode)if fill is not None:if isStringType(fill):fill = ImageColor.getcolor(fill, self.mode)if self.palette and not isinstance(fill, numbers.Number):fill = self.palette.getcolor(fill)fill = self.draw.draw_ink(fill, self.mode)return ink, filldef arc(self, xy, start, end, fill=None):"""Draw an arc."""ink, fill = self._getink(fill)if ink is not None:self.draw.draw_arc(xy, start, end, ink)def bitmap(self, xy, bitmap, fill=None):"""Draw a bitmap."""bitmap.load()ink, fill = self._getink(fill)if ink is None:ink = fillif ink is not None:self.draw.draw_bitmap(xy, bitmap.im, ink)def chord(self, xy, start, end, fill=None, outline=None):"""Draw a chord."""ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_chord(xy, start, end, fill, 1)if ink is not None:self.draw.draw_chord(xy, start, end, ink, 0)def ellipse(self, xy, fill=None, outline=None):"""Draw an ellipse."""ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_ellipse(xy, fill, 1)if ink is not None:self.draw.draw_ellipse(xy, ink, 0)def line(self, xy, fill=None, width=0):"""Draw a line, or a connected sequence of line segments."""ink, fill = self._getink(fill)if ink is not None:self.draw.draw_lines(xy, ink, width)def shape(self, shape, fill=None, outline=None):"""(Experimental) Draw a shape."""shape.close()ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_outline(shape, fill, 1)if ink is not None:self.draw.draw_outline(shape, ink, 0)def pieslice(self, xy, start, end, fill=None, outline=None):"""Draw a pieslice."""ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_pieslice(xy, start, end, fill, 1)if ink is not None:self.draw.draw_pieslice(xy, start, end, ink, 0)def point(self, xy, fill=None):"""Draw one or more individual pixels."""ink, fill = self._getink(fill)if ink is not None:self.draw.draw_points(xy, ink)def polygon(self, xy, fill=None, outline=None):"""Draw a polygon."""ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_polygon(xy, fill, 1)if ink is not None:self.draw.draw_polygon(xy, ink, 0)def rectangle(self, xy, fill=None, outline=None):"""Draw a rectangle."""ink, fill = self._getink(outline, fill)if fill is not None:self.draw.draw_rectangle(xy, fill, 1)if ink is not None:self.draw.draw_rectangle(xy, ink, 0)def _multiline_check(self, text):"""Draw text."""split_character = "\n" if isinstance(text, str) else b"\n"return split_character in textdef _multiline_split(self, text):split_character = "\n" if isinstance(text, str) else b"\n"return text.split(split_character)def text(self, xy, text, fill=None, font=None, anchor=None,*args, **kwargs):if self._multiline_check(text):return self.multiline_text(xy, text, fill, font, anchor,*args, **kwargs)ink, fill = self._getink(fill)if font is None:font = self.getfont()if ink is None:ink = fillif ink is not None:try:mask, offset = font.getmask2(text, self.fontmode, *args, **kwargs)xy = xy[0] + offset[0], xy[1] + offset[1]except AttributeError:try:mask = font.getmask(text, self.fontmode, *args, **kwargs)except TypeError:mask = font.getmask(text)self.draw.draw_bitmap(xy, mask, ink)def multiline_text(self, xy, text, fill=None, font=None, anchor=None,spacing=4, align="left", direction=None, features=None):widths = []max_width = 0lines = self._multiline_split(text)line_spacing = self.textsize('A', font=font)[1] + spacingfor line in lines:line_width, line_height = self.textsize(line, font)widths.append(line_width)max_width = max(max_width, line_width)left, top = xyfor idx, line in enumerate(lines):if align == "left":pass # left = xelif align == "center":left += (max_width - widths[idx]) / 2.0elif align == "right":left += (max_width - widths[idx])else:assert False, 'align must be "left", "center" or "right"'self.text((left, top), line, fill, font, anchor,direction=direction, features=features)top += line_spacingleft = xy[0]def textsize(self, text, font=None, spacing=4, direction=None,features=None):"""Get the size of a given string, in pixels."""if self._multiline_check(text):return self.multiline_textsize(text, font, spacing,direction, features)if font is None:font = self.getfont()return font.getsize(text, direction, features)def multiline_textsize(self, text, font=None, spacing=4, direction=None,features=None):max_width = 0lines = self._multiline_split(text)line_spacing = self.textsize('A', font=font)[1] + spacingfor line in lines:line_width, line_height = self.textsize(line, font, spacing,direction, features)max_width = max(max_width, line_width)return max_width, len(lines)*line_spacing - spacingdef Draw(im, mode=None):"""A simple 2D drawing interface for PIL images.:param im: The image to draw in.:param mode: Optional mode to use for color values. For RGBimages, this argument can be RGB or RGBA (to blend thedrawing into the image). For all other modes, this argumentmust be the same as the image mode. If omitted, the modedefaults to the mode of the image."""try:return im.getdraw(mode)except AttributeError:return ImageDraw(im, mode)# experimental access to the outline APItry:Outline = Image.core.outlineexcept AttributeError:Outline = Nonedef getdraw(im=None, hints=None):"""(Experimental) A more advanced 2D drawing interface for PIL images,based on the WCK interface.:param im: The image to draw in.:param hints: An optional list of hints.:returns: A (drawing context, drawing resource factory) tuple."""# FIXME: this needs more work!# FIXME: come up with a better 'hints' scheme.handler = Noneif not hints or "nicest" in hints:try:from . import _imagingagg as handlerexcept ImportError:passif handler is None:from . import ImageDraw2 as handlerif im:im = handler.Draw(im)return im, handlerdef floodfill(image, xy, value, border=None, thresh=0):"""(experimental) Fills a bounded region with a given color.:param image: Target image.:param xy: Seed position (a 2-item coordinate tuple). See:ref:`coordinate-system`.:param value: Fill color.:param border: Optional border value. If given, the region consists ofpixels with a color different from the border color. If not given,the region consists of pixels having the same color as the seedpixel.:param thresh: Optional threshold value which specifies a maximumtolerable difference of a pixel value from the 'background' inorder for it to be replaced. Useful for filling regions of non-homogeneous, but similar, colors."""# based on an implementation by Eric S. Raymondpixel = image.load()x, y = xytry:background = pixel[x, y]if _color_diff(value, background) <= thresh:return # seed point already has fill colorpixel[x, y] = valueexcept (ValueError, IndexError):return # seed point outside imageedge = [(x, y)]if border is None:while edge:newedge = []for (x, y) in edge:for (s, t) in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):try:p = pixel[s, t]except IndexError:passelse:if _color_diff(p, background) <= thresh:pixel[s, t] = valuenewedge.append((s, t))edge = newedgeelse:while edge:newedge = []for (x, y) in edge:for (s, t) in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):try:p = pixel[s, t]except IndexError:passelse:if p != value and p != border:pixel[s, t] = valuenewedge.append((s, t))edge = newedgedef _color_diff(rgb1, rgb2):"""Uses 1-norm distance to calculate difference between two rgb values."""return abs(rgb1[0]-rgb2[0]) + abs(rgb1[1]-rgb2[1]) + abs(rgb1[2]-rgb2[2])
123version https://git-lfs.github.com/spec/v1oid sha256:92915780d1267f6627d7acf2f53a54e3fcfb7a4379b048652a69935f09c2dde8size 3127123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108## The Python Imaging Library# $Id$## WCK-style drawing interface operations## History:# 2003-12-07 fl created# 2005-05-15 fl updated; added to PIL as ImageDraw2# 2005-05-15 fl added text support# 2005-05-20 fl added arc/chord/pieslice support## Copyright (c) 2003-2005 by Secret Labs AB# Copyright (c) 2003-2005 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, ImageColor, ImageDraw, ImageFont, ImagePathclass Pen(object):def __init__(self, color, width=1, opacity=255):self.color = ImageColor.getrgb(color)self.width = widthclass Brush(object):def __init__(self, color, opacity=255):self.color = ImageColor.getrgb(color)class Font(object):def __init__(self, color, file, size=12):# FIXME: add support for bitmap fontsself.color = ImageColor.getrgb(color)self.font = ImageFont.truetype(file, size)class Draw(object):def __init__(self, image, size=None, color=None):if not hasattr(image, "im"):image = Image.new(image, size, color)self.draw = ImageDraw.Draw(image)self.image = imageself.transform = Nonedef flush(self):return self.imagedef render(self, op, xy, pen, brush=None):# handle color argumentsoutline = fill = Nonewidth = 1if isinstance(pen, Pen):outline = pen.colorwidth = pen.widthelif isinstance(brush, Pen):outline = brush.colorwidth = brush.widthif isinstance(brush, Brush):fill = brush.colorelif isinstance(pen, Brush):fill = pen.color# handle transformationif self.transform:xy = ImagePath.Path(xy)xy.transform(self.transform)# render the itemif op == "line":self.draw.line(xy, fill=outline, width=width)else:getattr(self.draw, op)(xy, fill=fill, outline=outline)def settransform(self, offset):(xoffset, yoffset) = offsetself.transform = (1, 0, xoffset, 0, 1, yoffset)def arc(self, xy, start, end, *options):self.render("arc", xy, start, end, *options)def chord(self, xy, start, end, *options):self.render("chord", xy, start, end, *options)def ellipse(self, xy, *options):self.render("ellipse", xy, *options)def line(self, xy, *options):self.render("line", xy, *options)def pieslice(self, xy, start, end, *options):self.render("pieslice", xy, start, end, *options)def polygon(self, xy, *options):self.render("polygon", xy, *options)def rectangle(self, xy, *options):self.render("rectangle", xy, *options)def text(self, xy, text, font):if self.transform:xy = ImagePath.Path(xy)xy.transform(self.transform)self.draw.text(xy, text, font=font.font, fill=font.color)def textsize(self, text, font):return self.draw.textsize(text, font=font.font)
123version https://git-lfs.github.com/spec/v1oid sha256:790520fd4ce2e8f6de21a821066b5ceabe6974bbdebc502a6e7e82ff57c72f5csize 3195123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100## The Python Imaging Library.# $Id$## image enhancement classes## For a background, see "Image Processing By Interpolation and# Extrapolation", Paul Haeberli and Douglas Voorhies. Available# at http://www.graficaobscura.com/interp/index.html## History:# 1996-03-23 fl Created# 2009-06-16 fl Fixed mean calculation## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996.## See the README file for information on usage and redistribution.#from . import Image, ImageFilter, ImageStatclass _Enhance(object):def enhance(self, factor):"""Returns an enhanced image.:param factor: A floating point value controlling the enhancement.Factor 1.0 always returns a copy of the original image,lower factors mean less color (brightness, contrast,etc), and higher values more. There are no restrictionson this value.:rtype: :py:class:`~PIL.Image.Image`"""return Image.blend(self.degenerate, self.image, factor)class Color(_Enhance):"""Adjust image color balance.This class can be used to adjust the colour balance of an image, ina manner similar to the controls on a colour TV set. An enhancementfactor of 0.0 gives a black and white image. A factor of 1.0 givesthe original image."""def __init__(self, image):self.image = imageself.intermediate_mode = 'L'if 'A' in image.getbands():self.intermediate_mode = 'LA'self.degenerate = image.convert(self.intermediate_mode).convert(image.mode)class Contrast(_Enhance):"""Adjust image contrast.This class can be used to control the contrast of an image, similarto the contrast control on a TV set. An enhancement factor of 0.0gives a solid grey image. A factor of 1.0 gives the original image."""def __init__(self, image):self.image = imagemean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)self.degenerate = Image.new("L", image.size, mean).convert(image.mode)if 'A' in image.getbands():self.degenerate.putalpha(image.getchannel('A'))class Brightness(_Enhance):"""Adjust image brightness.This class can be used to control the brightness of an image. Anenhancement factor of 0.0 gives a black image. A factor of 1.0 gives theoriginal image."""def __init__(self, image):self.image = imageself.degenerate = Image.new(image.mode, image.size, 0)if 'A' in image.getbands():self.degenerate.putalpha(image.getchannel('A'))class Sharpness(_Enhance):"""Adjust image sharpness.This class can be used to adjust the sharpness of an image. Anenhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives theoriginal image, and a factor of 2.0 gives a sharpened image."""def __init__(self, image):self.image = imageself.degenerate = image.filter(ImageFilter.SMOOTH)if 'A' in image.getbands():self.degenerate.putalpha(image.getchannel('A'))
123version https://git-lfs.github.com/spec/v1oid sha256:cbbb724e4fbe9e5f3a6415b45697c8a0e835121036c24f6b43c274bf2044e210size 20584123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667## The Python Imaging Library.# $Id$## base class for image file handlers## history:# 1995-09-09 fl Created# 1996-03-11 fl Fixed load mechanism.# 1996-04-15 fl Added pcx/xbm decoders.# 1996-04-30 fl Added encoders.# 1996-12-14 fl Added load helpers# 1997-01-11 fl Use encode_to_file where possible# 1997-08-27 fl Flush output in _save# 1998-03-05 fl Use memory mapping for some modes# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"# 1999-05-31 fl Added image parser# 2000-10-12 fl Set readonly flag on memory-mapped images# 2002-03-20 fl Use better messages for common decoder errors# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available# 2003-10-30 fl Added StubImageFile class# 2004-02-25 fl Made incremental parser more robust## Copyright (c) 1997-2004 by Secret Labs AB# Copyright (c) 1995-2004 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imagefrom ._util import isPathimport ioimport osimport sysimport structMAXBLOCK = 65536SAFEBLOCK = 1024*1024LOAD_TRUNCATED_IMAGES = FalseERRORS = {-1: "image buffer overrun error",-2: "decoding error",-3: "unknown error",-8: "bad configuration",-9: "out of memory error"}def raise_ioerror(error):try:message = Image.core.getcodecstatus(error)except AttributeError:message = ERRORS.get(error)if not message:message = "decoder error %d" % errorraise IOError(message + " when reading image file")## --------------------------------------------------------------------# Helpersdef _tilesort(t):# sort on offsetreturn t[2]## --------------------------------------------------------------------# ImageFile base classclass ImageFile(Image.Image):"Base class for image file format handlers."def __init__(self, fp=None, filename=None):Image.Image.__init__(self)self._min_frame = 0self.tile = Noneself.readonly = 1 # until we know betterself.decoderconfig = ()self.decodermaxblock = MAXBLOCKif isPath(fp):# filenameself.fp = open(fp, "rb")self.filename = fpself._exclusive_fp = Trueelse:# streamself.fp = fpself.filename = filename# can be overriddenself._exclusive_fp = Nonetry:self._open()except (IndexError, # end of dataTypeError, # end of data (ord)KeyError, # unsupported modeEOFError, # got header but not the first framestruct.error) as v:# close the file only if we have opened it this constructorif self._exclusive_fp:self.fp.close()raise SyntaxError(v)if not self.mode or self.size[0] <= 0:raise SyntaxError("not identified by this driver")def draft(self, mode, size):"Set draft mode"passdef get_format_mimetype(self):if self.format is None:returnreturn Image.MIME.get(self.format.upper())def verify(self):"Check file integrity"# raise exception if something's wrong. must be called# directly after open, and closes file when finished.if self._exclusive_fp:self.fp.close()self.fp = Nonedef load(self):"Load image data based on tile list"pixel = Image.Image.load(self)if self.tile is None:raise IOError("cannot load this image")if not self.tile:return pixelself.map = Noneuse_mmap = self.filename and len(self.tile) == 1# As of pypy 2.1.0, memory mapping was failing here.use_mmap = use_mmap and not hasattr(sys, 'pypy_version_info')readonly = 0# look for read/seek overridestry:read = self.load_read# don't use mmap if there are custom read/seek functionsuse_mmap = Falseexcept AttributeError:read = self.fp.readtry:seek = self.load_seekuse_mmap = Falseexcept AttributeError:seek = self.fp.seekif use_mmap:# try memory mappingdecoder_name, extents, offset, args = self.tile[0]if decoder_name == "raw" and len(args) >= 3 and args[0] == self.mode \and args[0] in Image._MAPMODES:try:if hasattr(Image.core, "map"):# use built-in mapper WIN32 onlyself.map = Image.core.map(self.filename)self.map.seek(offset)self.im = self.map.readimage(self.mode, self.size, args[1], args[2])else:# use mmap, if possibleimport mmapwith open(self.filename, "r") as fp:self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)self.im = Image.core.map_buffer(self.map, self.size, decoder_name, extents, offset, args)readonly = 1# After trashing self.im, we might need to reload the palette data.if self.palette:self.palette.dirty = 1except (AttributeError, EnvironmentError, ImportError):self.map = Noneself.load_prepare()err_code = -3 # initialize to unknown errorif not self.map:# sort tiles in file orderself.tile.sort(key=_tilesort)try:# FIXME: This is a hack to handle TIFF's JpegTables tag.prefix = self.tile_prefixexcept AttributeError:prefix = b""for decoder_name, extents, offset, args in self.tile:decoder = Image._getdecoder(self.mode, decoder_name,args, self.decoderconfig)try:seek(offset)decoder.setimage(self.im, extents)if decoder.pulls_fd:decoder.setfd(self.fp)status, err_code = decoder.decode(b"")else:b = prefixwhile True:try:s = read(self.decodermaxblock)except (IndexError, struct.error): # truncated png/gifif LOAD_TRUNCATED_IMAGES:breakelse:raise IOError("image file is truncated")if not s: # truncated jpegif LOAD_TRUNCATED_IMAGES:breakelse:self.tile = []raise IOError("image file is truncated ""(%d bytes not processed)" % len(b))b = b + sn, err_code = decoder.decode(b)if n < 0:breakb = b[n:]finally:# Need to cleanup here to prevent leaksdecoder.cleanup()self.tile = []self.readonly = readonlyself.load_end()if self._exclusive_fp and self._close_exclusive_fp_after_loading:self.fp.close()self.fp = Noneif not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:# still raised if decoder fails to return anythingraise_ioerror(err_code)return Image.Image.load(self)def load_prepare(self):# create image memory if necessaryif not self.im or\self.im.mode != self.mode or self.im.size != self.size:self.im = Image.core.new(self.mode, self.size)# create palette (optional)if self.mode == "P":Image.Image.load(self)def load_end(self):# may be overriddenpass# may be defined for contained formats# def load_seek(self, pos):# pass# may be defined for blocked formats (e.g. PNG)# def load_read(self, bytes):# passdef _seek_check(self, frame):if (frame < self._min_frame or# Only check upper limit on frames if additional seek operations# are not required to do so(not (hasattr(self, "_n_frames") and self._n_frames is None) andframe >= self.n_frames+self._min_frame)):raise EOFError("attempt to seek outside sequence")return self.tell() != frameclass StubImageFile(ImageFile):"""Base class for stub image loaders.A stub loader is an image loader that can identify files of acertain format, but relies on external code to load the file."""def _open(self):raise NotImplementedError("StubImageFile subclass must implement _open")def load(self):loader = self._load()if loader is None:raise IOError("cannot find loader for this %s file" % self.format)image = loader.load(self)assert image is not None# become the other object (!)self.__class__ = image.__class__self.__dict__ = image.__dict__def _load(self):"(Hook) Find actual image loader."raise NotImplementedError("StubImageFile subclass must implement _load")class Parser(object):"""Incremental image parser. This class implements the standardfeed/close consumer interface."""incremental = Noneimage = Nonedata = Nonedecoder = Noneoffset = 0finished = 0def reset(self):"""(Consumer) Reset the parser. Note that you can only call thismethod immediately after you've created a parser; parserinstances cannot be reused."""assert self.data is None, "cannot reuse parsers"def feed(self, data):"""(Consumer) Feed data to the parser.:param data: A string buffer.:exception IOError: If the parser failed to parse the image file."""# collect dataif self.finished:returnif self.data is None:self.data = dataelse:self.data = self.data + data# parse what we haveif self.decoder:if self.offset > 0:# skip headerskip = min(len(self.data), self.offset)self.data = self.data[skip:]self.offset = self.offset - skipif self.offset > 0 or not self.data:returnn, e = self.decoder.decode(self.data)if n < 0:# end of streamself.data = Noneself.finished = 1if e < 0:# decoding errorself.image = Noneraise_ioerror(e)else:# end of imagereturnself.data = self.data[n:]elif self.image:# if we end up here with no decoder, this file cannot# be incrementally parsed. wait until we've gotten all# available datapasselse:# attempt to open this filetry:with io.BytesIO(self.data) as fp:im = Image.open(fp)except IOError:# traceback.print_exc()pass # not enough dataelse:flag = hasattr(im, "load_seek") or hasattr(im, "load_read")if flag or len(im.tile) != 1:# custom load code, or multiple tilesself.decode = Noneelse:# initialize decoderim.load_prepare()d, e, o, a = im.tile[0]im.tile = []self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)self.decoder.setimage(im.im, e)# calculate decoder offsetself.offset = oif self.offset <= len(self.data):self.data = self.data[self.offset:]self.offset = 0self.image = imdef __enter__(self):return selfdef __exit__(self, *args):self.close()def close(self):"""(Consumer) Close the stream.:returns: An image object.:exception IOError: If the parser failed to parse the image file eitherbecause it cannot be identified or cannot bedecoded."""# finish decodingif self.decoder:# get rid of what's left in the buffersself.feed(b"")self.data = self.decoder = Noneif not self.finished:raise IOError("image was incomplete")if not self.image:raise IOError("cannot parse this image")if self.data:# incremental parsing not possible; reopen the file# not that we have all datawith io.BytesIO(self.data) as fp:try:self.image = Image.open(fp)finally:self.image.load()return self.image# --------------------------------------------------------------------def _save(im, fp, tile, bufsize=0):"""Helper to save image based on tile list:param im: Image object.:param fp: File object.:param tile: Tile list.:param bufsize: Optional buffer size"""im.load()if not hasattr(im, "encoderconfig"):im.encoderconfig = ()tile.sort(key=_tilesort)# FIXME: make MAXBLOCK a configuration parameter# It would be great if we could have the encoder specify what it needs# But, it would need at least the image size in most cases. RawEncode is# a tricky case.bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.cif fp == sys.stdout:fp.flush()returntry:fh = fp.fileno()fp.flush()except (AttributeError, io.UnsupportedOperation):# compress to Python file-compatible objectfor e, b, o, a in tile:e = Image._getencoder(im.mode, e, a, im.encoderconfig)if o > 0:fp.seek(o, 0)e.setimage(im.im, b)if e.pushes_fd:e.setfd(fp)l, s = e.encode_to_pyfd()else:while True:l, s, d = e.encode(bufsize)fp.write(d)if s:breakif s < 0:raise IOError("encoder error %d when writing image file" % s)e.cleanup()else:# slight speedup: compress to real file objectfor e, b, o, a in tile:e = Image._getencoder(im.mode, e, a, im.encoderconfig)if o > 0:fp.seek(o, 0)e.setimage(im.im, b)if e.pushes_fd:e.setfd(fp)l, s = e.encode_to_pyfd()else:s = e.encode_to_file(fh, bufsize)if s < 0:raise IOError("encoder error %d when writing image file" % s)e.cleanup()if hasattr(fp, "flush"):fp.flush()def _safe_read(fp, size):"""Reads large blocks in a safe way. Unlike fp.read(n), this functiondoesn't trust the user. If the requested size is larger thanSAFEBLOCK, the file is read block by block.:param fp: File handle. Must implement a <b>read</b> method.:param size: Number of bytes to read.:returns: A string containing up to <i>size</i> bytes of data."""if size <= 0:return b""if size <= SAFEBLOCK:return fp.read(size)data = []while size > 0:block = fp.read(min(size, SAFEBLOCK))if not block:breakdata.append(block)size -= len(block)return b"".join(data)class PyCodecState(object):def __init__(self):self.xsize = 0self.ysize = 0self.xoff = 0self.yoff = 0def extents(self):return (self.xoff, self.yoff,self.xoff+self.xsize, self.yoff+self.ysize)class PyDecoder(object):"""Python implementation of a format decoder. Override this class andadd the decoding logic in the `decode` method.See :ref:`Writing Your Own File Decoder in Python<file-decoders-py>`"""_pulls_fd = Falsedef __init__(self, mode, *args):self.im = Noneself.state = PyCodecState()self.fd = Noneself.mode = modeself.init(args)def init(self, args):"""Override to perform decoder specific initialization:param args: Array of args items from the tile entry:returns: None"""self.args = args@propertydef pulls_fd(self):return self._pulls_fddef decode(self, buffer):"""Override to perform the decoding process.:param buffer: A bytes object with the data to be decoded. If `handles_eof`is set, then `buffer` will be empty and `self.fd` will be set.:returns: A tuple of (bytes consumed, errcode). If finished with decodingreturn <0 for the bytes consumed. Err codes are from `ERRORS`"""raise NotImplementedError()def cleanup(self):"""Override to perform decoder specific cleanup:returns: None"""passdef setfd(self, fd):"""Called from ImageFile to set the python file-like object:param fd: A python file-like object:returns: None"""self.fd = fddef setimage(self, im, extents=None):"""Called from ImageFile to set the core output image for the decoder:param im: A core image object:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectanglefor this tile:returns: None"""# following c codeself.im = imif extents:(x0, y0, x1, y1) = extentselse:(x0, y0, x1, y1) = (0, 0, 0, 0)if x0 == 0 and x1 == 0:self.state.xsize, self.state.ysize = self.im.sizeelse:self.state.xoff = x0self.state.yoff = y0self.state.xsize = x1 - x0self.state.ysize = y1 - y0if self.state.xsize <= 0 or self.state.ysize <= 0:raise ValueError("Size cannot be negative")if (self.state.xsize + self.state.xoff > self.im.size[0] orself.state.ysize + self.state.yoff > self.im.size[1]):raise ValueError("Tile cannot extend outside image")def set_as_raw(self, data, rawmode=None):"""Convenience method to set the internal image from a stream of raw data:param data: Bytes to be set:param rawmode: The rawmode to be used for the decoder. If not specified,it will default to the mode of the image:returns: None"""if not rawmode:rawmode = self.moded = Image._getdecoder(self.mode, 'raw', (rawmode))d.setimage(self.im, self.state.extents())s = d.decode(data)if s[0] >= 0:raise ValueError("not enough image data")if s[1] != 0:raise ValueError("cannot decode image data")
123version https://git-lfs.github.com/spec/v1oid sha256:d7e6f5562f127f18166683bf8dbc136869ce15cd84c47143c2284560180bc852size 15383123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486## The Python Imaging Library.# $Id$## standard filters## History:# 1995-11-27 fl Created# 2002-06-08 fl Added rank and mode filters# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call## Copyright (c) 1997-2003 by Secret Labs AB.# Copyright (c) 1995-2002 by Fredrik Lundh.## See the README file for information on usage and redistribution.#from __future__ import divisionimport functoolstry:import numpyexcept ImportError: # pragma: no covernumpy = Noneclass Filter(object):passclass MultibandFilter(Filter):passclass Kernel(MultibandFilter):"""Create a convolution kernel. The current version onlysupports 3x3 and 5x5 integer and floating point kernels.In the current version, kernels can only be applied to"L" and "RGB" images.:param size: Kernel size, given as (width, height). In the currentversion, this must be (3,3) or (5,5).:param kernel: A sequence containing kernel weights.:param scale: Scale factor. If given, the result for each pixel isdivided by this value. the default is the sum of thekernel weights.:param offset: Offset. If given, this value is added to the result,after it has been divided by the scale factor."""name = "Kernel"def __init__(self, size, kernel, scale=None, offset=0):if scale is None:# default scale is sum of kernelscale = functools.reduce(lambda a, b: a+b, kernel)if size[0] * size[1] != len(kernel):raise ValueError("not enough coefficients in kernel")self.filterargs = size, scale, offset, kerneldef filter(self, image):if image.mode == "P":raise ValueError("cannot filter palette images")return image.filter(*self.filterargs)class BuiltinFilter(Kernel):def __init__(self):passclass RankFilter(Filter):"""Create a rank filter. The rank filter sorts all pixels ina window of the given size, and returns the **rank**'th value.:param size: The kernel size, in pixels.:param rank: What pixel value to pick. Use 0 for a min filter,``size * size / 2`` for a median filter, ``size * size - 1``for a max filter, etc."""name = "Rank"def __init__(self, size, rank):self.size = sizeself.rank = rankdef filter(self, image):if image.mode == "P":raise ValueError("cannot filter palette images")image = image.expand(self.size//2, self.size//2)return image.rankfilter(self.size, self.rank)class MedianFilter(RankFilter):"""Create a median filter. Picks the median pixel value in a window with thegiven size.:param size: The kernel size, in pixels."""name = "Median"def __init__(self, size=3):self.size = sizeself.rank = size*size//2class MinFilter(RankFilter):"""Create a min filter. Picks the lowest pixel value in a window with thegiven size.:param size: The kernel size, in pixels."""name = "Min"def __init__(self, size=3):self.size = sizeself.rank = 0class MaxFilter(RankFilter):"""Create a max filter. Picks the largest pixel value in a window with thegiven size.:param size: The kernel size, in pixels."""name = "Max"def __init__(self, size=3):self.size = sizeself.rank = size*size-1class ModeFilter(Filter):"""Create a mode filter. Picks the most frequent pixel value in a box with thegiven size. Pixel values that occur only once or twice are ignored; if nopixel value occurs more than twice, the original pixel value is preserved.:param size: The kernel size, in pixels."""name = "Mode"def __init__(self, size=3):self.size = sizedef filter(self, image):return image.modefilter(self.size)class GaussianBlur(MultibandFilter):"""Gaussian blur filter.:param radius: Blur radius."""name = "GaussianBlur"def __init__(self, radius=2):self.radius = radiusdef filter(self, image):return image.gaussian_blur(self.radius)class BoxBlur(MultibandFilter):"""Blurs the image by setting each pixel to the average value of the pixelsin a square box extending radius pixels in each direction.Supports float radius of arbitrary size. Uses an optimized implementationwhich runs in linear time relative to the size of the imagefor any radius value.:param radius: Size of the box in one direction. Radius 0 does not blur,returns an identical image. Radius 1 takes 1 pixelin each direction, i.e. 9 pixels in total."""name = "BoxBlur"def __init__(self, radius):self.radius = radiusdef filter(self, image):return image.box_blur(self.radius)class UnsharpMask(MultibandFilter):"""Unsharp mask filter.See Wikipedia's entry on `digital unsharp masking`_ for an explanation ofthe parameters.:param radius: Blur Radius:param percent: Unsharp strength, in percent:param threshold: Threshold controls the minimum brightness change thatwill be sharpened.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking"""name = "UnsharpMask"def __init__(self, radius=2, percent=150, threshold=3):self.radius = radiusself.percent = percentself.threshold = thresholddef filter(self, image):return image.unsharp_mask(self.radius, self.percent, self.threshold)class BLUR(BuiltinFilter):name = "Blur"filterargs = (5, 5), 16, 0, (1, 1, 1, 1, 1,1, 0, 0, 0, 1,1, 0, 0, 0, 1,1, 0, 0, 0, 1,1, 1, 1, 1, 1)class CONTOUR(BuiltinFilter):name = "Contour"filterargs = (3, 3), 1, 255, (-1, -1, -1,-1, 8, -1,-1, -1, -1)class DETAIL(BuiltinFilter):name = "Detail"filterargs = (3, 3), 6, 0, (0, -1, 0,-1, 10, -1,0, -1, 0)class EDGE_ENHANCE(BuiltinFilter):name = "Edge-enhance"filterargs = (3, 3), 2, 0, (-1, -1, -1,-1, 10, -1,-1, -1, -1)class EDGE_ENHANCE_MORE(BuiltinFilter):name = "Edge-enhance More"filterargs = (3, 3), 1, 0, (-1, -1, -1,-1, 9, -1,-1, -1, -1)class EMBOSS(BuiltinFilter):name = "Emboss"filterargs = (3, 3), 1, 128, (-1, 0, 0,0, 1, 0,0, 0, 0)class FIND_EDGES(BuiltinFilter):name = "Find Edges"filterargs = (3, 3), 1, 0, (-1, -1, -1,-1, 8, -1,-1, -1, -1)class SHARPEN(BuiltinFilter):name = "Sharpen"filterargs = (3, 3), 16, 0, (-2, -2, -2,-2, 32, -2,-2, -2, -2)class SMOOTH(BuiltinFilter):name = "Smooth"filterargs = (3, 3), 13, 0, (1, 1, 1,1, 5, 1,1, 1, 1)class SMOOTH_MORE(BuiltinFilter):name = "Smooth More"filterargs = (5, 5), 100, 0, (1, 1, 1, 1, 1,1, 5, 5, 5, 1,1, 5, 44, 5, 1,1, 5, 5, 5, 1,1, 1, 1, 1, 1)class Color3DLUT(MultibandFilter):"""Three-dimensional color lookup table.Transforms 3-channel pixels using the values of the channels as coordinatesin the 3D lookup table and interpolating the nearest elements.This method allows you to apply almost any color transformationin constant time by using pre-calculated decimated tables... versionadded:: 5.2.0:param size: Size of the table. One int or tuple of (int, int, int).Minimal size in any dimension is 2, maximum is 65.:param table: Flat lookup table. A list of ``channels * size**3``float elements or a list of ``size**3`` channels-sizedtuples with floats. Channels are changed first,then first dimension, then second, then third.Value 0.0 corresponds lowest value of output, 1.0 highest.:param channels: Number of channels in the table. Could be 3 or 4.Default is 3.:param target_mode: A mode for the result image. Should have not lessthan ``channels`` channels. Default is ``None``,which means that mode wouldn't be changed."""name = "Color 3D LUT"def __init__(self, size, table, channels=3, target_mode=None, **kwargs):if channels not in (3, 4):raise ValueError("Only 3 or 4 output channels are supported")self.size = size = self._check_size(size)self.channels = channelsself.mode = target_mode# Hidden flag `_copy_table=False` could be used to avoid extra copying# of the table if the table is specially made for the constructor.copy_table = kwargs.get('_copy_table', True)items = size[0] * size[1] * size[2]wrong_size = Falseif numpy and isinstance(table, numpy.ndarray):if copy_table:table = table.copy()if table.shape in [(items * channels,), (items, channels),(size[2], size[1], size[0], channels)]:table = table.reshape(items * channels)else:wrong_size = Trueelse:if copy_table:table = list(table)# Convert to a flat listif table and isinstance(table[0], (list, tuple)):table, raw_table = [], tablefor pixel in raw_table:if len(pixel) != channels:raise ValueError("The elements of the table should ""have a length of {}.".format(channels))table.extend(pixel)if wrong_size or len(table) != items * channels:raise ValueError("The table should have either channels * size**3 float items ""or size**3 items of channels-sized tuples with floats. ""Table should be: {}x{}x{}x{}. Actual length: {}".format(channels, size[0], size[1], size[2], len(table)))self.table = table@staticmethoddef _check_size(size):try:_, _, _ = sizeexcept ValueError:raise ValueError("Size should be either an integer or ""a tuple of three integers.")except TypeError:size = (size, size, size)size = [int(x) for x in size]for size1D in size:if not 2 <= size1D <= 65:raise ValueError("Size should be in [2, 65] range.")return size@classmethoddef generate(cls, size, callback, channels=3, target_mode=None):"""Generates new LUT using provided callback.:param size: Size of the table. Passed to the constructor.:param callback: Function with three parameters which correspondthree color channels. Will be called ``size**3``times with values from 0.0 to 1.0 and should returna tuple with ``channels`` elements.:param channels: The number of channels which should return callback.:param target_mode: Passed to the constructor of the resultinglookup table."""size1D, size2D, size3D = cls._check_size(size)if channels not in (3, 4):raise ValueError("Only 3 or 4 output channels are supported")table = [0] * (size1D * size2D * size3D * channels)idx_out = 0for b in range(size3D):for g in range(size2D):for r in range(size1D):table[idx_out:idx_out + channels] = callback(r / (size1D-1), g / (size2D-1), b / (size3D-1))idx_out += channelsreturn cls((size1D, size2D, size3D), table, channels=channels,target_mode=target_mode, _copy_table=False)def transform(self, callback, with_normals=False, channels=None,target_mode=None):"""Transforms the table values using provided callback and returnsa new LUT with altered values.:param callback: A function which takes old lookup table valuesand returns a new set of values. The numberof arguments which function should take is``self.channels`` or ``3 + self.channels``if ``with_normals`` flag is set.Should return a tuple of ``self.channels`` or``channels`` elements if it is set.:param with_normals: If true, ``callback`` will be called withcoordinates in the color cube as the firstthree arguments. Otherwise, ``callback``will be called only with actual color values.:param channels: The number of channels in the resulting lookup table.:param target_mode: Passed to the constructor of the resultinglookup table."""if channels not in (None, 3, 4):raise ValueError("Only 3 or 4 output channels are supported")ch_in = self.channelsch_out = channels or ch_insize1D, size2D, size3D = self.sizetable = [0] * (size1D * size2D * size3D * ch_out)idx_in = 0idx_out = 0for b in range(size3D):for g in range(size2D):for r in range(size1D):values = self.table[idx_in:idx_in + ch_in]if with_normals:values = callback(r / (size1D-1), g / (size2D-1),b / (size3D-1), *values)else:values = callback(*values)table[idx_out:idx_out + ch_out] = valuesidx_in += ch_inidx_out += ch_outreturn type(self)(self.size, table, channels=ch_out,target_mode=target_mode or self.mode,_copy_table=False)def __repr__(self):r = ["{} from {}".format(self.__class__.__name__,self.table.__class__.__name__),"size={:d}x{:d}x{:d}".format(*self.size),"channels={:d}".format(self.channels),]if self.mode:r.append("target_mode={}".format(self.mode))return "<{}>".format(" ".join(r))def filter(self, image):from . import Imagereturn image.color_lut_3d(self.mode or image.mode, Image.LINEAR, self.channels,self.size[0], self.size[1], self.size[2], self.table)
123version https://git-lfs.github.com/spec/v1oid sha256:0e277cc9f25691acced47a95aa1d7818cadf812e95833ab44a98e75a4e744586size 21369123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471## The Python Imaging Library.# $Id$## PIL raster font management## History:# 1996-08-07 fl created (experimental)# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3# 1999-02-06 fl rewrote most font management stuff in C# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)# 2001-02-17 fl added freetype support# 2001-05-09 fl added TransposedFont wrapper class# 2002-03-04 fl make sure we have a "L" or "1" font# 2002-12-04 fl skip non-directory entries in the system path# 2003-04-29 fl add embedded default font# 2003-09-27 fl added support for truetype charmap encodings## Todo:# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)## Copyright (c) 1997-2003 by Secret Labs AB# Copyright (c) 1996-2003 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imagefrom ._util import isDirectory, isPath, py3import osimport sysLAYOUT_BASIC = 0LAYOUT_RAQM = 1class _imagingft_not_installed(object):# module placeholderdef __getattr__(self, id):raise ImportError("The _imagingft C module is not installed")try:from . import _imagingft as coreexcept ImportError:core = _imagingft_not_installed()# FIXME: add support for pilfont2 format (see FontFile.py)# --------------------------------------------------------------------# Font metrics format:# "PILfont" LF# fontdescriptor LF# (optional) key=value... LF# "DATA" LF# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)## To place a character, cut out srcbox and paste at dstbox,# relative to the character position. Then move the character# position according to dx, dy.# --------------------------------------------------------------------class ImageFont(object):"PIL font wrapper"def _load_pilfont(self, filename):with open(filename, "rb") as fp:for ext in (".png", ".gif", ".pbm"):try:fullname = os.path.splitext(filename)[0] + extimage = Image.open(fullname)except:passelse:if image and image.mode in ("1", "L"):breakelse:raise IOError("cannot find glyph data file")self.file = fullnamereturn self._load_pilfont_data(fp, image)def _load_pilfont_data(self, file, image):# read PILfont headerif file.readline() != b"PILfont\n":raise SyntaxError("Not a PILfont file")file.readline().split(b";")self.info = [] # FIXME: should be a dictionarywhile True:s = file.readline()if not s or s == b"DATA\n":breakself.info.append(s)# read PILfont metricsdata = file.read(256*20)# check imageif image.mode not in ("1", "L"):raise TypeError("invalid font image mode")image.load()self.font = Image.core.font(image.im, data)def getsize(self, text, *args, **kwargs):return self.font.getsize(text)def getmask(self, text, mode="", *args, **kwargs):return self.font.getmask(text, mode)### Wrapper for FreeType fonts. Application code should use the# <b>truetype</b> factory function to create font objects.class FreeTypeFont(object):"FreeType font wrapper (requires _imagingft service)"def __init__(self, font=None, size=10, index=0, encoding="",layout_engine=None):# FIXME: use service provider insteadself.path = fontself.size = sizeself.index = indexself.encoding = encodingif layout_engine not in (LAYOUT_BASIC, LAYOUT_RAQM):layout_engine = LAYOUT_BASICif core.HAVE_RAQM:layout_engine = LAYOUT_RAQMif layout_engine == LAYOUT_RAQM and not core.HAVE_RAQM:layout_engine = LAYOUT_BASICself.layout_engine = layout_engineif isPath(font):self.font = core.getfont(font, size, index, encoding, layout_engine=layout_engine)else:self.font_bytes = font.read()self.font = core.getfont("", size, index, encoding, self.font_bytes, layout_engine)def _multiline_split(self, text):split_character = "\n" if isinstance(text, str) else b"\n"return text.split(split_character)def getname(self):return self.font.family, self.font.styledef getmetrics(self):return self.font.ascent, self.font.descentdef getsize(self, text, direction=None, features=None):size, offset = self.font.getsize(text, direction, features)return (size[0] + offset[0], size[1] + offset[1])def getsize_multiline(self, text, direction=None, spacing=4, features=None):max_width = 0lines = self._multiline_split(text)line_spacing = self.getsize('A')[1] + spacingfor line in lines:line_width, line_height = self.getsize(line, direction, features)max_width = max(max_width, line_width)return max_width, len(lines)*line_spacing - spacingdef getoffset(self, text):return self.font.getsize(text)[1]def getmask(self, text, mode="", direction=None, features=None):return self.getmask2(text, mode, direction=direction, features=features)[0]def getmask2(self, text, mode="", fill=Image.core.fill, direction=None, features=None, *args, **kwargs):size, offset = self.font.getsize(text, direction, features)im = fill("L", size, 0)self.font.render(text, im.id, mode == "1", direction, features)return im, offsetdef font_variant(self, font=None, size=None, index=None, encoding=None,layout_engine=None):"""Create a copy of this FreeTypeFont object,using any specified arguments to override the settings.Parameters are identical to the parameters used to initialize thisobject.:return: A FreeTypeFont object."""return FreeTypeFont(font=self.path if font is None else font,size=self.size if size is None else size,index=self.index if index is None else index,encoding=self.encoding if encoding is None else encoding,layout_engine=self.layout_engine if layout_engine is None else layout_engine)class TransposedFont(object):"Wrapper for writing rotated or mirrored text"def __init__(self, font, orientation=None):"""Wrapper that creates a transposed font from any existing fontobject.:param font: A font object.:param orientation: An optional orientation. If given, this shouldbe one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM,Image.ROTATE_90, Image.ROTATE_180, or Image.ROTATE_270."""self.font = fontself.orientation = orientation # any 'transpose' argument, or Nonedef getsize(self, text, *args, **kwargs):w, h = self.font.getsize(text)if self.orientation in (Image.ROTATE_90, Image.ROTATE_270):return h, wreturn w, hdef getmask(self, text, mode="", *args, **kwargs):im = self.font.getmask(text, mode, *args, **kwargs)if self.orientation is not None:return im.transpose(self.orientation)return imdef load(filename):"""Load a font file. This function loads a font object from the givenbitmap font file, and returns the corresponding font object.:param filename: Name of font file.:return: A font object.:exception IOError: If the file could not be read."""f = ImageFont()f._load_pilfont(filename)return fdef truetype(font=None, size=10, index=0, encoding="",layout_engine=None):"""Load a TrueType or OpenType font from a file or file-like object,and create a font object.This function loads a font object from the given file or file-likeobject, and creates a font object for a font of the given size.This function requires the _imagingft service.:param font: A filename or file-like object containing a TrueType font.Under Windows, if the file is not found in this filename,the loader also looks in Windows :file:`fonts/` directory.:param size: The requested size, in points.:param index: Which font face to load (default is first available face).:param encoding: Which font encoding to use (default is Unicode). Commonencodings are "unic" (Unicode), "symb" (MicrosoftSymbol), "ADOB" (Adobe Standard), "ADBE" (Adobe Expert),and "armn" (Apple Roman). See the FreeType documentationfor more information.:param layout_engine: Which layout engine to use, if available:`ImageFont.LAYOUT_BASIC` or `ImageFont.LAYOUT_RAQM`.:return: A font object.:exception IOError: If the file could not be read."""try:return FreeTypeFont(font, size, index, encoding, layout_engine)except IOError:ttf_filename = os.path.basename(font)dirs = []if sys.platform == "win32":# check the windows font repository# NOTE: must use uppercase WINDIR, to work around bugs in# 1.5.2's os.environ.get()windir = os.environ.get("WINDIR")if windir:dirs.append(os.path.join(windir, "fonts"))elif sys.platform in ('linux', 'linux2'):lindirs = os.environ.get("XDG_DATA_DIRS", "")if not lindirs:# According to the freedesktop spec, XDG_DATA_DIRS should# default to /usr/sharelindirs = '/usr/share'dirs += [os.path.join(lindir, "fonts")for lindir in lindirs.split(":")]elif sys.platform == 'darwin':dirs += ['/Library/Fonts', '/System/Library/Fonts',os.path.expanduser('~/Library/Fonts')]ext = os.path.splitext(ttf_filename)[1]first_font_with_a_different_extension = Nonefor directory in dirs:for walkroot, walkdir, walkfilenames in os.walk(directory):for walkfilename in walkfilenames:if ext and walkfilename == ttf_filename:fontpath = os.path.join(walkroot, walkfilename)return FreeTypeFont(fontpath, size, index, encoding, layout_engine)elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:fontpath = os.path.join(walkroot, walkfilename)if os.path.splitext(fontpath)[1] == '.ttf':return FreeTypeFont(fontpath, size, index, encoding, layout_engine)if not ext and first_font_with_a_different_extension is None:first_font_with_a_different_extension = fontpathif first_font_with_a_different_extension:return FreeTypeFont(first_font_with_a_different_extension, size,index, encoding, layout_engine)raisedef load_path(filename):"""Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for abitmap font along the Python path.:param filename: Name of font file.:return: A font object.:exception IOError: If the file could not be read."""for directory in sys.path:if isDirectory(directory):if not isinstance(filename, str):if py3:filename = filename.decode("utf-8")else:filename = filename.encode("utf-8")try:return load(os.path.join(directory, filename))except IOError:passraise IOError("cannot find font file")def load_default():"""Load a "better than nothing" default font... versionadded:: 1.1.4:return: A font object."""from io import BytesIOimport base64f = ImageFont()f._load_pilfont_data(# courB08BytesIO(base64.b64decode(b'''UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEABgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAALAAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUAAAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAABACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8ABAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYAAAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAHAAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAAZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABvAAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT//gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5AAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAAAP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAGAAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsABgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAAAMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAFAAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYABgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEvAAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcAAAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAAAUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sABQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP////kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYAAP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAFAAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAABmwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGnAAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUAAAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7AAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAAAv/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYAAAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJAAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAACDgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZAAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/+wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5AAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD////7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAGAAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgABQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAAAm0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAACeQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAGAAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgABgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALTAAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0AAALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAAAu4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oABf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP////cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYAAP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQAAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoALQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5AAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUAAABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5AAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAAAP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAGAAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwAEgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAKAJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAApQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAGAAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////+QAGAAIAzgAKANUAEw==''')), Image.open(BytesIO(base64.b64decode(b'''iVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4uMc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9M43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0gLeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4FIUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAABu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791NAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMxin0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9SjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAYAYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tty8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkGABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqYlODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3AAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47c4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD//yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSwpEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1TvoJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMRevta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAAAAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//Gc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDRw7IkEbzhVQAAAABJRU5ErkJggg=='''))))return f
123version https://git-lfs.github.com/spec/v1oid sha256:abbc13bf687eb7afb62aa28a54884b83794d4d3021968e396c4ad3dfaf291b3fsize 21501234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980## The Python Imaging Library# $Id$## screen grabber (macOS and Windows only)## History:# 2001-04-26 fl created# 2001-09-17 fl use builtin driver, if present# 2002-11-19 fl added grabclipboard support## Copyright (c) 2001-2002 by Secret Labs AB# Copyright (c) 2001-2002 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imageimport sysif sys.platform not in ["win32", "darwin"]:raise ImportError("ImageGrab is macOS and Windows only")if sys.platform == "win32":grabber = Image.core.grabscreenelif sys.platform == "darwin":import osimport tempfileimport subprocessdef grab(bbox=None):if sys.platform == "darwin":fh, filepath = tempfile.mkstemp('.png')os.close(fh)subprocess.call(['screencapture', '-x', filepath])im = Image.open(filepath)im.load()os.unlink(filepath)else:size, data = grabber()im = Image.frombytes("RGB", size, data,# RGB, 32-bit line padding, origin lower left corner"raw", "BGR", (size[0]*3 + 3) & -4, -1)if bbox:im = im.crop(bbox)return imdef grabclipboard():if sys.platform == "darwin":fh, filepath = tempfile.mkstemp('.jpg')os.close(fh)commands = ["set theFile to (open for access POSIX file \""+filepath+"\" with write permission)","try","write (the clipboard as JPEG picture) to theFile","end try","close access theFile"]script = ["osascript"]for command in commands:script += ["-e", command]subprocess.call(script)im = Noneif os.stat(filepath).st_size != 0:im = Image.open(filepath)im.load()os.unlink(filepath)return imelse:data = Image.core.grabclipboard()if isinstance(data, bytes):from . import BmpImagePluginimport ioreturn BmpImagePlugin.DibImageFile(io.BytesIO(data))return data
123version https://git-lfs.github.com/spec/v1oid sha256:9372af7314b9566d3b21656766aab4171f1c79507531db019581e82d8ae90f2bsize 7463123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271## The Python Imaging Library# $Id$## a simple math add-on for the Python Imaging Library## History:# 1999-02-15 fl Original PIL Plus release# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6# 2005-09-12 fl Fixed int() and float() for Python 2.4.1## Copyright (c) 1999-2005 by Secret Labs AB# Copyright (c) 2005 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Image, _imagingmathfrom ._util import py3try:import builtinsexcept ImportError:import __builtin__builtins = __builtin__VERBOSE = 0def _isconstant(v):return isinstance(v, int) or isinstance(v, float)class _Operand(object):"""Wraps an image operand, providing standard operators"""def __init__(self, im):self.im = imdef __fixup(self, im1):# convert image to suitable modeif isinstance(im1, _Operand):# argument was an image.if im1.im.mode in ("1", "L"):return im1.im.convert("I")elif im1.im.mode in ("I", "F"):return im1.imelse:raise ValueError("unsupported mode: %s" % im1.im.mode)else:# argument was a constantif _isconstant(im1) and self.im.mode in ("1", "L", "I"):return Image.new("I", self.im.size, im1)else:return Image.new("F", self.im.size, im1)def apply(self, op, im1, im2=None, mode=None):im1 = self.__fixup(im1)if im2 is None:# unary operationout = Image.new(mode or im1.mode, im1.size, None)im1.load()try:op = getattr(_imagingmath, op+"_"+im1.mode)except AttributeError:raise TypeError("bad operand type for '%s'" % op)_imagingmath.unop(op, out.im.id, im1.im.id)else:# binary operationim2 = self.__fixup(im2)if im1.mode != im2.mode:# convert both arguments to floating pointif im1.mode != "F":im1 = im1.convert("F")if im2.mode != "F":im2 = im2.convert("F")if im1.mode != im2.mode:raise ValueError("mode mismatch")if im1.size != im2.size:# crop both arguments to a common sizesize = (min(im1.size[0], im2.size[0]),min(im1.size[1], im2.size[1]))if im1.size != size:im1 = im1.crop((0, 0) + size)if im2.size != size:im2 = im2.crop((0, 0) + size)out = Image.new(mode or im1.mode, size, None)else:out = Image.new(mode or im1.mode, im1.size, None)im1.load()im2.load()try:op = getattr(_imagingmath, op+"_"+im1.mode)except AttributeError:raise TypeError("bad operand type for '%s'" % op)_imagingmath.binop(op, out.im.id, im1.im.id, im2.im.id)return _Operand(out)# unary operatorsdef __bool__(self):# an image is "true" if it contains at least one non-zero pixelreturn self.im.getbbox() is not Noneif not py3:# Provide __nonzero__ for pre-Py3k__nonzero__ = __bool__del __bool__def __abs__(self):return self.apply("abs", self)def __pos__(self):return selfdef __neg__(self):return self.apply("neg", self)# binary operatorsdef __add__(self, other):return self.apply("add", self, other)def __radd__(self, other):return self.apply("add", other, self)def __sub__(self, other):return self.apply("sub", self, other)def __rsub__(self, other):return self.apply("sub", other, self)def __mul__(self, other):return self.apply("mul", self, other)def __rmul__(self, other):return self.apply("mul", other, self)def __truediv__(self, other):return self.apply("div", self, other)def __rtruediv__(self, other):return self.apply("div", other, self)def __mod__(self, other):return self.apply("mod", self, other)def __rmod__(self, other):return self.apply("mod", other, self)def __pow__(self, other):return self.apply("pow", self, other)def __rpow__(self, other):return self.apply("pow", other, self)if not py3:# Provide __div__ and __rdiv__ for pre-Py3k__div__ = __truediv____rdiv__ = __rtruediv__del __truediv__del __rtruediv__# bitwisedef __invert__(self):return self.apply("invert", self)def __and__(self, other):return self.apply("and", self, other)def __rand__(self, other):return self.apply("and", other, self)def __or__(self, other):return self.apply("or", self, other)def __ror__(self, other):return self.apply("or", other, self)def __xor__(self, other):return self.apply("xor", self, other)def __rxor__(self, other):return self.apply("xor", other, self)def __lshift__(self, other):return self.apply("lshift", self, other)def __rshift__(self, other):return self.apply("rshift", self, other)# logicaldef __eq__(self, other):return self.apply("eq", self, other)def __ne__(self, other):return self.apply("ne", self, other)def __lt__(self, other):return self.apply("lt", self, other)def __le__(self, other):return self.apply("le", self, other)def __gt__(self, other):return self.apply("gt", self, other)def __ge__(self, other):return self.apply("ge", self, other)# conversionsdef imagemath_int(self):return _Operand(self.im.convert("I"))def imagemath_float(self):return _Operand(self.im.convert("F"))# logicaldef imagemath_equal(self, other):return self.apply("eq", self, other, mode="I")def imagemath_notequal(self, other):return self.apply("ne", self, other, mode="I")def imagemath_min(self, other):return self.apply("min", self, other)def imagemath_max(self, other):return self.apply("max", self, other)def imagemath_convert(self, mode):return _Operand(self.im.convert(mode))ops = {}for k, v in list(globals().items()):if k[:10] == "imagemath_":ops[k[10:]] = vdef eval(expression, _dict={}, **kw):"""Evaluates an image expression.:param expression: A string containing a Python-style expression.:param options: Values to add to the evaluation context. Youcan either use a dictionary, or one or more keywordarguments.:return: The evaluated expression. This is usually an image object, but canalso be an integer, a floating point value, or a pixel tuple,depending on the expression."""# build execution namespaceargs = ops.copy()args.update(_dict)args.update(kw)for k, v in list(args.items()):if hasattr(v, "im"):args[k] = _Operand(v)out = builtins.eval(expression, args)try:return out.imexcept AttributeError:return out
123version https://git-lfs.github.com/spec/v1oid sha256:7eb1e6fa1a6d0fba02c966dac0ab58b236f7355f021cd5e7f11d1dcab012b401size 155812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455## The Python Imaging Library.# $Id$## standard mode descriptors## History:# 2006-03-20 fl Added## Copyright (c) 2006 by Secret Labs AB.# Copyright (c) 2006 by Fredrik Lundh.## See the README file for information on usage and redistribution.## mode descriptor cache_modes = Noneclass ModeDescriptor(object):"""Wrapper for mode strings."""def __init__(self, mode, bands, basemode, basetype):self.mode = modeself.bands = bandsself.basemode = basemodeself.basetype = basetypedef __str__(self):return self.modedef getmode(mode):"""Gets a mode descriptor for the given mode."""global _modesif not _modes:# initialize mode cachefrom . import Imagemodes = {}# core modesfor m, (basemode, basetype, bands) in Image._MODEINFO.items():modes[m] = ModeDescriptor(m, bands, basemode, basetype)# extra experimental modesmodes["RGBa"] = ModeDescriptor("RGBa", ("R", "G", "B", "a"), "RGB", "L")modes["LA"] = ModeDescriptor("LA", ("L", "A"), "L", "L")modes["La"] = ModeDescriptor("La", ("L", "a"), "L", "L")modes["PA"] = ModeDescriptor("PA", ("P", "A"), "RGB", "L")# mapping modesmodes["I;16"] = ModeDescriptor("I;16", "I", "L", "L")modes["I;16L"] = ModeDescriptor("I;16L", "I", "L", "L")modes["I;16B"] = ModeDescriptor("I;16B", "I", "L", "L")# set global mode cache atomically_modes = modesreturn _modes[mode]
123version https://git-lfs.github.com/spec/v1oid sha256:6e08f799a2346b65c883b037fcad87ff968dd78125c2abb8d37f06290a84c202size 8370123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250# A binary morphology add-on for the Python Imaging Library## History:# 2014-06-04 Initial version.## Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>from __future__ import print_functionfrom . import Image, _imagingmorphimport reLUT_SIZE = 1 << 9class LutBuilder(object):"""A class for building a MorphLut from a descriptive languageThe input patterns is a list of a strings sequences like these::4:(....1.111)->1(whitespaces including linebreaks are ignored). The option 4describes a series of symmetry operations (in this case a4-rotation), the pattern is described by:- . or X - Ignore- 1 - Pixel is on- 0 - Pixel is offThe result of the operation is described after "->" string.The default is to return the current pixel value, which isreturned if no other match is found.Operations:- 4 - 4 way rotation- N - Negate- 1 - Dummy op for no other operation (an op must always be given)- M - MirroringExample::lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])lut = lb.build_lut()"""def __init__(self, patterns=None, op_name=None):if patterns is not None:self.patterns = patternselse:self.patterns = []self.lut = Noneif op_name is not None:known_patterns = {'corner': ['1:(... ... ...)->0','4:(00. 01. ...)->1'],'dilation4': ['4:(... .0. .1.)->1'],'dilation8': ['4:(... .0. .1.)->1','4:(... .0. ..1)->1'],'erosion4': ['4:(... .1. .0.)->0'],'erosion8': ['4:(... .1. .0.)->0','4:(... .1. ..0)->0'],'edge': ['1:(... ... ...)->0','4:(.0. .1. ...)->1','4:(01. .1. ...)->1']}if op_name not in known_patterns:raise Exception('Unknown pattern '+op_name+'!')self.patterns = known_patterns[op_name]def add_patterns(self, patterns):self.patterns += patternsdef build_default_lut(self):symbols = [0, 1]m = 1 << 4 # pos of current pixelself.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))def get_lut(self):return self.lutdef _string_permute(self, pattern, permutation):"""string_permute takes a pattern and a permutation and returns thestring permuted according to the permutation list."""assert(len(permutation) == 9)return ''.join(pattern[p] for p in permutation)def _pattern_permute(self, basic_pattern, options, basic_result):"""pattern_permute takes a basic pattern and its result and clonesthe pattern according to the modifications described in the $optionsparameter. It returns a list of all cloned patterns."""patterns = [(basic_pattern, basic_result)]# rotationsif '4' in options:res = patterns[-1][1]for i in range(4):patterns.append((self._string_permute(patterns[-1][0], [6, 3, 0,7, 4, 1,8, 5, 2]), res))# mirrorif 'M' in options:n = len(patterns)for pattern, res in patterns[0:n]:patterns.append((self._string_permute(pattern, [2, 1, 0,5, 4, 3,8, 7, 6]), res))# negateif 'N' in options:n = len(patterns)for pattern, res in patterns[0:n]:# Swap 0 and 1pattern = (pattern.replace('0', 'Z').replace('1', '0').replace('Z', '1'))res = 1-int(res)patterns.append((pattern, res))return patternsdef build_lut(self):"""Compile all patterns into a morphology lut.TBD :Build based on (file) morphlut:modify_lut"""self.build_default_lut()patterns = []# Parse and create symmetries of the patterns stringsfor p in self.patterns:m = re.search(r'(\w*):?\s*\((.+?)\)\s*->\s*(\d)', p.replace('\n', ''))if not m:raise Exception('Syntax error in pattern "'+p+'"')options = m.group(1)pattern = m.group(2)result = int(m.group(3))# Get rid of spacespattern = pattern.replace(' ', '').replace('\n', '')patterns += self._pattern_permute(pattern, options, result)# # Debugging# for p, r in patterns:# print(p, r)# print('--')# compile the patterns into regular expressions for speedfor i, pattern in enumerate(patterns):p = pattern[0].replace('.', 'X').replace('X', '[01]')p = re.compile(p)patterns[i] = (p, pattern[1])# Step through table and find patterns that match.# Note that all the patterns are searched. The last one# caught overridesfor i in range(LUT_SIZE):# Build the bit patternbitpattern = bin(i)[2:]bitpattern = ('0'*(9-len(bitpattern)) + bitpattern)[::-1]for p, r in patterns:if p.match(bitpattern):self.lut[i] = [0, 1][r]return self.lutclass MorphOp(object):"""A class for binary morphological operators"""def __init__(self,lut=None,op_name=None,patterns=None):"""Create a binary morphological operator"""self.lut = lutif op_name is not None:self.lut = LutBuilder(op_name=op_name).build_lut()elif patterns is not None:self.lut = LutBuilder(patterns=patterns).build_lut()def apply(self, image):"""Run a single morphological operation on an imageReturns a tuple of the number of changed pixels and themorphed image"""if self.lut is None:raise Exception('No operator loaded')if image.mode != 'L':raise Exception('Image must be binary, meaning it must use mode L')outimage = Image.new(image.mode, image.size, None)count = _imagingmorph.apply(bytes(self.lut), image.im.id, outimage.im.id)return count, outimagedef match(self, image):"""Get a list of coordinates matching the morphological operation onan image.Returns a list of tuples of (x,y) coordinatesof all matching pixels. See :ref:`coordinate-system`."""if self.lut is None:raise Exception('No operator loaded')if image.mode != 'L':raise Exception('Image must be binary, meaning it must use mode L')return _imagingmorph.match(bytes(self.lut), image.im.id)def get_on_pixels(self, image):"""Get a list of all turned on pixels in a binary imageReturns a list of tuples of (x,y) coordinatesof all matching pixels. See :ref:`coordinate-system`."""if image.mode != 'L':raise Exception('Image must be binary, meaning it must use mode L')return _imagingmorph.get_on_pixels(image.im.id)def load_lut(self, filename):"""Load an operator from an mrl file"""with open(filename, 'rb') as f:self.lut = bytearray(f.read())if len(self.lut) != LUT_SIZE:self.lut = Noneraise Exception('Wrong size operator file!')def save_lut(self, filename):"""Save an operator to an mrl file"""if self.lut is None:raise Exception('No operator loaded')with open(filename, 'wb') as f:f.write(self.lut)def set_lut(self, lut):"""Set the lut from an external source"""self.lut = lut
123version https://git-lfs.github.com/spec/v1oid sha256:00838db4d37c4600110035a604fa22c1acc7fa0ba43040ac3b482fe725d43affsize 16106123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529## The Python Imaging Library.# $Id$## standard image operations## History:# 2001-10-20 fl Created# 2001-10-23 fl Added autocontrast operator# 2001-12-18 fl Added Kevin's fit operator# 2004-03-14 fl Fixed potential division by zero in equalize# 2005-05-05 fl Fixed equalize for low number of values## Copyright (c) 2001-2004 by Secret Labs AB# Copyright (c) 2001-2004 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imagefrom ._util import isStringTypeimport operatorimport functoolsimport warnings## helpersdef _border(border):if isinstance(border, tuple):if len(border) == 2:left, top = right, bottom = borderelif len(border) == 4:left, top, right, bottom = borderelse:left = top = right = bottom = borderreturn left, top, right, bottomdef _color(color, mode):if isStringType(color):from . import ImageColorcolor = ImageColor.getcolor(color, mode)return colordef _lut(image, lut):if image.mode == "P":# FIXME: apply to lookup table, not image dataraise NotImplementedError("mode P support coming soon")elif image.mode in ("L", "RGB"):if image.mode == "RGB" and len(lut) == 256:lut = lut + lut + lutreturn image.point(lut)else:raise IOError("not supported for this image mode")## actionsdef autocontrast(image, cutoff=0, ignore=None):"""Maximize (normalize) image contrast. This function calculates ahistogram of the input image, removes **cutoff** percent of thelightest and darkest pixels from the histogram, and remaps the imageso that the darkest pixel becomes black (0), and the lightestbecomes white (255).:param image: The image to process.:param cutoff: How many percent to cut off from the histogram.:param ignore: The background pixel value (use None for no background).:return: An image."""histogram = image.histogram()lut = []for layer in range(0, len(histogram), 256):h = histogram[layer:layer+256]if ignore is not None:# get rid of outlierstry:h[ignore] = 0except TypeError:# assume sequencefor ix in ignore:h[ix] = 0if cutoff:# cut off pixels from both ends of the histogram# get number of pixelsn = 0for ix in range(256):n = n + h[ix]# remove cutoff% pixels from the low endcut = n * cutoff // 100for lo in range(256):if cut > h[lo]:cut = cut - h[lo]h[lo] = 0else:h[lo] -= cutcut = 0if cut <= 0:break# remove cutoff% samples from the hi endcut = n * cutoff // 100for hi in range(255, -1, -1):if cut > h[hi]:cut = cut - h[hi]h[hi] = 0else:h[hi] -= cutcut = 0if cut <= 0:break# find lowest/highest samples after preprocessingfor lo in range(256):if h[lo]:breakfor hi in range(255, -1, -1):if h[hi]:breakif hi <= lo:# don't botherlut.extend(list(range(256)))else:scale = 255.0 / (hi - lo)offset = -lo * scalefor ix in range(256):ix = int(ix * scale + offset)if ix < 0:ix = 0elif ix > 255:ix = 255lut.append(ix)return _lut(image, lut)def colorize(image, black, white):"""Colorize grayscale image. The **black** and **white**arguments should be RGB tuples; this function calculates a colorwedge mapping all black pixels in the source image to the firstcolor, and all white pixels to the second color.:param image: The image to colorize.:param black: The color to use for black input pixels.:param white: The color to use for white input pixels.:return: An image."""assert image.mode == "L"black = _color(black, "RGB")white = _color(white, "RGB")red = []green = []blue = []for i in range(256):red.append(black[0]+i*(white[0]-black[0])//255)green.append(black[1]+i*(white[1]-black[1])//255)blue.append(black[2]+i*(white[2]-black[2])//255)image = image.convert("RGB")return _lut(image, red + green + blue)def crop(image, border=0):"""Remove border from image. The same amount of pixels are removedfrom all four sides. This function works on all image modes... seealso:: :py:meth:`~PIL.Image.Image.crop`:param image: The image to crop.:param border: The number of pixels to remove.:return: An image."""left, top, right, bottom = _border(border)return image.crop((left, top, image.size[0]-right, image.size[1]-bottom))def scale(image, factor, resample=Image.NEAREST):"""Returns a rescaled image by a specific factor given in parameter.A factor greater than 1 expands the image, between 0 and 1 contracts theimage.:param image: The image to rescale.:param factor: The expansion factor, as a float.:param resample: An optional resampling filter. Same values possible asin the PIL.Image.resize function.:returns: An :py:class:`~PIL.Image.Image` object."""if factor == 1:return image.copy()elif factor <= 0:raise ValueError("the factor must be greater than 0")else:size = (int(round(factor * image.width)),int(round(factor * image.height)))return image.resize(size, resample)def deform(image, deformer, resample=Image.BILINEAR):"""Deform the image.:param image: The image to deform.:param deformer: A deformer object. Any object that implements a**getmesh** method can be used.:param resample: An optional resampling filter. Same values possible asin the PIL.Image.transform function.:return: An image."""return image.transform(image.size, Image.MESH, deformer.getmesh(image), resample)def equalize(image, mask=None):"""Equalize the image histogram. This function applies a non-linearmapping to the input image, in order to create a uniformdistribution of grayscale values in the output image.:param image: The image to equalize.:param mask: An optional mask. If given, only the pixels selected bythe mask are included in the analysis.:return: An image."""if image.mode == "P":image = image.convert("RGB")h = image.histogram(mask)lut = []for b in range(0, len(h), 256):histo = [_f for _f in h[b:b+256] if _f]if len(histo) <= 1:lut.extend(list(range(256)))else:step = (functools.reduce(operator.add, histo) - histo[-1]) // 255if not step:lut.extend(list(range(256)))else:n = step // 2for i in range(256):lut.append(n // step)n = n + h[i+b]return _lut(image, lut)def expand(image, border=0, fill=0):"""Add border to the image:param image: The image to expand.:param border: Border width, in pixels.:param fill: Pixel fill value (a color value). Default is 0 (black).:return: An image."""left, top, right, bottom = _border(border)width = left + image.size[0] + rightheight = top + image.size[1] + bottomout = Image.new(image.mode, (width, height), _color(fill, image.mode))out.paste(image, (left, top))return outdef fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):"""Returns a sized and cropped version of the image, cropped to therequested aspect ratio and size.This function was contributed by Kevin Cazabon.:param image: The image to size and crop.:param size: The requested output size in pixels, given as a(width, height) tuple.:param method: What resampling method to use. Default is:py:attr:`PIL.Image.NEAREST`.:param bleed: Remove a border around the outside of the image (from allfour edges. The value is a decimal percentage (use 0.01 forone percent). The default value is 0 (no border).:param centering: Control the cropping position. Use (0.5, 0.5) forcenter cropping (e.g. if cropping the width, take 50% offof the left side, and therefore 50% off the right side).(0.0, 0.0) will crop from the top left corner (i.e. ifcropping the width, take all of the crop off of the rightside, and if cropping the height, take all of it off thebottom). (1.0, 0.0) will crop from the bottom leftcorner, etc. (i.e. if cropping the width, take all of thecrop off the left side, and if cropping the height takenone from the top, and therefore all off the bottom).:return: An image."""# by Kevin Cazabon, Feb 17/2000# kevin@cazabon.com# http://www.cazabon.com# ensure inputs are validif not isinstance(centering, list):centering = [centering[0], centering[1]]if centering[0] > 1.0 or centering[0] < 0.0:centering[0] = 0.50if centering[1] > 1.0 or centering[1] < 0.0:centering[1] = 0.50if bleed > 0.49999 or bleed < 0.0:bleed = 0.0# calculate the area to use for resizing and cropping, subtracting# the 'bleed' around the edges# number of pixels to trim off on Top and Bottom, Left and RightbleedPixels = (int((float(bleed) * float(image.size[0])) + 0.5),int((float(bleed) * float(image.size[1])) + 0.5))liveArea = (0, 0, image.size[0], image.size[1])if bleed > 0.0:liveArea = (bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,image.size[1] - bleedPixels[1] - 1)liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])# calculate the aspect ratio of the liveArealiveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])# calculate the aspect ratio of the output imageaspectRatio = float(size[0]) / float(size[1])# figure out if the sides or top/bottom will be cropped offif liveAreaAspectRatio >= aspectRatio:# liveArea is wider than what's needed, crop the sidescropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)cropHeight = liveSize[1]else:# liveArea is taller than what's needed, crop the top and bottomcropWidth = liveSize[0]cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)# make the cropleftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))if leftSide < 0:leftSide = 0topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))if topSide < 0:topSide = 0out = image.crop((leftSide, topSide, leftSide + cropWidth, topSide + cropHeight))# resize the image and return itreturn out.resize(size, method)def flip(image):"""Flip the image vertically (top to bottom).:param image: The image to flip.:return: An image."""return image.transpose(Image.FLIP_TOP_BOTTOM)def grayscale(image):"""Convert the image to grayscale.:param image: The image to convert.:return: An image."""return image.convert("L")def invert(image):"""Invert (negate) the image.:param image: The image to invert.:return: An image."""lut = []for i in range(256):lut.append(255-i)return _lut(image, lut)def mirror(image):"""Flip image horizontally (left to right).:param image: The image to mirror.:return: An image."""return image.transpose(Image.FLIP_LEFT_RIGHT)def posterize(image, bits):"""Reduce the number of bits for each color channel.:param image: The image to posterize.:param bits: The number of bits to keep for each channel (1-8).:return: An image."""lut = []mask = ~(2**(8-bits)-1)for i in range(256):lut.append(i & mask)return _lut(image, lut)def solarize(image, threshold=128):"""Invert all pixel values above a threshold.:param image: The image to solarize.:param threshold: All pixels above this greyscale level are inverted.:return: An image."""lut = []for i in range(256):if i < threshold:lut.append(i)else:lut.append(255-i)return _lut(image, lut)# --------------------------------------------------------------------# PIL USM components, from Kevin Cazabon.def gaussian_blur(im, radius=None):""" PIL_usm.gblur(im, [radius])"""warnings.warn('PIL.ImageOps.gaussian_blur is deprecated. ''Use PIL.ImageFilter.GaussianBlur instead. ''This function will be removed in a future version.',DeprecationWarning)if radius is None:radius = 5.0im.load()return im.im.gaussian_blur(radius)def gblur(im, radius=None):""" PIL_usm.gblur(im, [radius])"""warnings.warn('PIL.ImageOps.gblur is deprecated. ''Use PIL.ImageFilter.GaussianBlur instead. ''This function will be removed in a future version.',DeprecationWarning)return gaussian_blur(im, radius)def unsharp_mask(im, radius=None, percent=None, threshold=None):""" PIL_usm.usm(im, [radius, percent, threshold])"""warnings.warn('PIL.ImageOps.unsharp_mask is deprecated. ''Use PIL.ImageFilter.UnsharpMask instead. ''This function will be removed in a future version.',DeprecationWarning)if radius is None:radius = 5.0if percent is None:percent = 150if threshold is None:threshold = 3im.load()return im.im.unsharp_mask(radius, percent, threshold)def usm(im, radius=None, percent=None, threshold=None):""" PIL_usm.usm(im, [radius, percent, threshold])"""warnings.warn('PIL.ImageOps.usm is deprecated. ''Use PIL.ImageFilter.UnsharpMask instead. ''This function will be removed in a future version.',DeprecationWarning)return unsharp_mask(im, radius, percent, threshold)def box_blur(image, radius):"""Blur the image by setting each pixel to the average value of the pixelsin a square box extending radius pixels in each direction.Supports float radius of arbitrary size. Uses an optimized implementationwhich runs in linear time relative to the size of the imagefor any radius value.:param image: The image to blur.:param radius: Size of the box in one direction. Radius 0 does not blur,returns an identical image. Radius 1 takes 1 pixelin each direction, i.e. 9 pixels in total.:return: An image."""warnings.warn('PIL.ImageOps.box_blur is deprecated. ''Use PIL.ImageFilter.BoxBlur instead. ''This function will be removed in a future version.',DeprecationWarning)image.load()return image._new(image.im.box_blur(radius))
123version https://git-lfs.github.com/spec/v1oid sha256:a59fc6407c4c14d9e591c3050db76da3e233f3a156831427cae81fc51c568d26size 6321123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216## The Python Imaging Library.# $Id$## image palette object## History:# 1996-03-11 fl Rewritten.# 1997-01-03 fl Up and running.# 1997-08-23 fl Added load hack# 2001-04-16 fl Fixed randint shadow bug in random()## Copyright (c) 1997-2001 by Secret Labs AB# Copyright (c) 1996-1997 by Fredrik Lundh## See the README file for information on usage and redistribution.#import arrayfrom . import ImageColor, GimpPaletteFile, GimpGradientFile, PaletteFileclass ImagePalette(object):"""Color palette for palette mapped images:param mode: The mode to use for the Palette. See::ref:`concept-modes`. Defaults to "RGB":param palette: An optional palette. If given, it must be a bytearray,an array or a list of ints between 0-255 and of length ``size``times the number of colors in ``mode``. The list must be alignedby channel (All R values must be contiguous in the list before Gand B values.) Defaults to 0 through 255 per channel.:param size: An optional palette size. If given, it cannot be equal toor greater than 256. Defaults to 0."""def __init__(self, mode="RGB", palette=None, size=0):self.mode = modeself.rawmode = None # if set, palette contains raw dataself.palette = palette or bytearray(range(256))*len(self.mode)self.colors = {}self.dirty = Noneif ((size == 0 and len(self.mode)*256 != len(self.palette)) or(size != 0 and size != len(self.palette))):raise ValueError("wrong palette size")def copy(self):new = ImagePalette()new.mode = self.modenew.rawmode = self.rawmodeif self.palette is not None:new.palette = self.palette[:]new.colors = self.colors.copy()new.dirty = self.dirtyreturn newdef getdata(self):"""Get palette contents in format suitable # for the low-level``im.putpalette`` primitive... warning:: This method is experimental."""if self.rawmode:return self.rawmode, self.palettereturn self.mode + ";L", self.tobytes()def tobytes(self):"""Convert palette to bytes... warning:: This method is experimental."""if self.rawmode:raise ValueError("palette contains raw palette data")if isinstance(self.palette, bytes):return self.palettearr = array.array("B", self.palette)if hasattr(arr, 'tobytes'):return arr.tobytes()return arr.tostring()# Declare tostring as an alias for tobytestostring = tobytesdef getcolor(self, color):"""Given an rgb tuple, allocate palette entry... warning:: This method is experimental."""if self.rawmode:raise ValueError("palette contains raw palette data")if isinstance(color, tuple):try:return self.colors[color]except KeyError:# allocate new color slotif isinstance(self.palette, bytes):self.palette = bytearray(self.palette)index = len(self.colors)if index >= 256:raise ValueError("cannot allocate more than 256 colors")self.colors[color] = indexself.palette[index] = color[0]self.palette[index+256] = color[1]self.palette[index+512] = color[2]self.dirty = 1return indexelse:raise ValueError("unknown color specifier: %r" % color)def save(self, fp):"""Save palette to text file... warning:: This method is experimental."""if self.rawmode:raise ValueError("palette contains raw palette data")if isinstance(fp, str):fp = open(fp, "w")fp.write("# Palette\n")fp.write("# Mode: %s\n" % self.mode)for i in range(256):fp.write("%d" % i)for j in range(i*len(self.mode), (i+1)*len(self.mode)):try:fp.write(" %d" % self.palette[j])except IndexError:fp.write(" 0")fp.write("\n")fp.close()# --------------------------------------------------------------------# Internaldef raw(rawmode, data):palette = ImagePalette()palette.rawmode = rawmodepalette.palette = datapalette.dirty = 1return palette# --------------------------------------------------------------------# Factoriesdef make_linear_lut(black, white):lut = []if black == 0:for i in range(256):lut.append(white*i//255)else:raise NotImplementedError # FIXMEreturn lutdef make_gamma_lut(exp):lut = []for i in range(256):lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5))return lutdef negative(mode="RGB"):palette = list(range(256))palette.reverse()return ImagePalette(mode, palette * len(mode))def random(mode="RGB"):from random import randintpalette = []for i in range(256*len(mode)):palette.append(randint(0, 255))return ImagePalette(mode, palette)def sepia(white="#fff0c0"):r, g, b = ImageColor.getrgb(white)r = make_linear_lut(0, r)g = make_linear_lut(0, g)b = make_linear_lut(0, b)return ImagePalette("RGB", r + g + b)def wedge(mode="RGB"):return ImagePalette(mode, list(range(256)) * len(mode))def load(filename):# FIXME: supports GIMP gradients onlywith open(filename, "rb") as fp:for paletteHandler in [GimpPaletteFile.GimpPaletteFile,GimpGradientFile.GimpGradientFile,PaletteFile.PaletteFile]:try:fp.seek(0)lut = paletteHandler(fp).getpalette()if lut:breakexcept (SyntaxError, ValueError):# import traceback# traceback.print_exc()passelse:raise IOError("cannot load palette")return lut # data, rawmode
123version https://git-lfs.github.com/spec/v1oid sha256:20f52693fd52743e4d8e9656bb00c40ccad122afe2cd6ae189cceaef31602e5fsize 3371234567891011121314151617181920## The Python Imaging Library# $Id$## path interface## History:# 1996-11-04 fl Created# 2002-04-14 fl Added documentation stub class## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996.## See the README file for information on usage and redistribution.#from . import ImagePath = Image.core.path
123version https://git-lfs.github.com/spec/v1oid sha256:242e5f11c027f6ad2bddb1f7e9af58801430c8f210d5f77c457ad81e858b5b69size 6321123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212## 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 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)## Copyright (c) 2006 by Secret Labs AB# Copyright (c) 2006 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imagefrom ._util import isPath, py3from io import BytesIOimport sysqt_versions = [['5', 'PyQt5'],['4', 'PyQt4'],['side', 'PySide']]# If a version has already been imported, attempt it firstqt_versions.sort(key=lambda qt_version: qt_version[1] in sys.modules, reverse=True)for qt_version, qt_module in qt_versions:try:if qt_module == 'PyQt5':from PyQt5.QtGui import QImage, qRgba, QPixmapfrom PyQt5.QtCore import QBuffer, QIODeviceelif qt_module == 'PyQt4':from PyQt4.QtGui import QImage, qRgba, QPixmapfrom PyQt4.QtCore import QBuffer, QIODeviceelif qt_module == 'PySide':from PySide.QtGui import QImage, qRgba, QPixmapfrom PySide.QtCore import QBuffer, QIODeviceexcept (ImportError, RuntimeError):continueqt_is_installed = Truebreakelse:qt_is_installed = Falseqt_version = Nonedef 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)def fromqimage(im):""":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 alha channel with png# otherwise ppm is more friendly with Image.openif im.hasAlphaChannel():im.save(buffer, 'png')else:im.save(buffer, 'ppm')b = BytesIO()try:b.write(buffer.data())except TypeError:# workaround for Python 2b.write(str(buffer.data()))buffer.close()b.seek(0)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)# return Image.open(bytes_io)def align8to32(bytes, width, mode):"""converts each scanline of data from 8 bit to 32 bit aligned"""bits_per_pixel = {'1': 1,'L': 8,'P': 8,}[mode]# calculate bytes per line and the extra padding if neededbits_per_line = bits_per_pixel * widthfull_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 luckif not extra_padding:return bytesnew_data = []for i in range(len(bytes) // bytes_per_line):new_data.append(bytes[i*bytes_per_line:(i+1)*bytes_per_line] + b'\x00' * extra_padding)return b''.join(new_data)def _toqclass_helper(im):data = Nonecolortable = None# handle filename, if given instead of image nameif hasattr(im, "toUtf8"):# FIXME - is this really the best way to do this?if py3:im = str(im.toUtf8(), "utf-8")else:im = unicode(im.toUtf8(), "utf-8")if isPath(im):im = Image.open(im)if im.mode == "1":format = QImage.Format_Monoelif im.mode == "L":format = QImage.Format_Indexed8colortable = []for i in range(256):colortable.append(rgb(i, i, i))elif im.mode == "P":format = QImage.Format_Indexed8colortable = []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_RGB32elif im.mode == "RGBA":try:data = im.tobytes("raw", "BGRA")except SystemError:# workaround for earlier versionsr, g, b, a = im.split()im = Image.merge("RGBA", (b, g, r, a))format = QImage.Format_ARGB32else:raise ValueError("unsupported image mode %r" % im.mode)__data = data or align8to32(im.tobytes(), im.size[0], im.mode)return {'data': __data, 'im': im, 'format': format, 'colortable': colortable}if qt_is_installed:class ImageQt(QImage):def __init__(self, im):"""An PIL image wrapper for Qt. This is a subclass of PyQt's QImageclass.:param im: A PIL Image object, or a file name (given either as Pythonstring or a PyQt string object)."""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/1370self.__data = im_data['data']QImage.__init__(self,self.__data, im_data['im'].size[0],im_data['im'].size[1], im_data['format'])if im_data['colortable']:self.setColorTable(im_data['colortable'])def toqimage(im):return ImageQt(im)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 causesif im.mode == 'RGB':im = im.convert('RGBA')qimage = toqimage(im)return QPixmap.fromImage(qimage)
123version https://git-lfs.github.com/spec/v1oid sha256:7e9ef3881f0beb38445f3f1b4eb539b1809d1a767b3b300310eb2f09ddfb55cesize 12401234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556## The Python Imaging Library.# $Id$## sequence support classes## history:# 1997-02-20 fl Created## Copyright (c) 1997 by Secret Labs AB.# Copyright (c) 1997 by Fredrik Lundh.## See the README file for information on usage and redistribution.###class Iterator(object):"""This class implements an iterator object that can be used to loopover an image sequence.You can use the ``[]`` operator to access elements by index. This operatorwill raise an :py:exc:`IndexError` if you try to access a nonexistentframe.:param im: An image object."""def __init__(self, im):if not hasattr(im, "seek"):raise AttributeError("im must have seek method")self.im = imself.position = 0def __getitem__(self, ix):try:self.im.seek(ix)return self.imexcept EOFError:raise IndexError # end of sequencedef __iter__(self):return selfdef __next__(self):try:self.im.seek(self.position)self.position += 1return self.imexcept EOFError:raise StopIterationdef next(self):return self.__next__()
123version https://git-lfs.github.com/spec/v1oid sha256:b47ead223f2387ffe139e014a67443812894d7991f85a39aa1cf1c4447b93935size 5262123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194## The Python Imaging Library.# $Id$## im.show() drivers## History:# 2008-04-06 fl Created## Copyright (c) Secret Labs AB 2008.## See the README file for information on usage and redistribution.#from __future__ import print_functionfrom PIL import Imageimport osimport sysif sys.version_info.major >= 3:from shlex import quoteelse:from pipes import quote_viewers = []def register(viewer, order=1):try:if issubclass(viewer, Viewer):viewer = viewer()except TypeError:pass # raised if viewer wasn't a classif order > 0:_viewers.append(viewer)elif order < 0:_viewers.insert(0, viewer)def show(image, title=None, **options):r"""Display a given image.:param image: An image object.:param title: Optional title. Not all viewers can display the title.:param \**options: Additional viewer options.:returns: True if a suitable viewer was found, false otherwise."""for viewer in _viewers:if viewer.show(image, title=title, **options):return 1return 0class Viewer(object):"""Base class for viewers."""# main apidef show(self, image, **options):# save temporary image to diskif image.mode[:4] == "I;16":# @PIL88 @PIL101# "I;16" isn't an 'official' mode, but we still want to# provide a simple way to show 16-bit images.base = "L"# FIXME: auto-contrast if max() > 255?else:base = Image.getmodebase(image.mode)if base != image.mode and image.mode != "1" and image.mode != "RGBA":image = image.convert(base)return self.show_image(image, **options)# hook methodsformat = Noneoptions = {}def get_format(self, image):"""Return format name, or None to save as PGM/PPM"""return self.formatdef get_command(self, file, **options):raise NotImplementedErrordef save_image(self, image):"""Save to temporary file, and return filename"""return image._dump(format=self.get_format(image), **self.options)def show_image(self, image, **options):"""Display given image"""return self.show_file(self.save_image(image), **options)def show_file(self, file, **options):"""Display given file"""os.system(self.get_command(file, **options))return 1# --------------------------------------------------------------------if sys.platform == "win32":class WindowsViewer(Viewer):format = "BMP"def get_command(self, file, **options):return ('start "Pillow" /WAIT "%s" ''&& ping -n 2 127.0.0.1 >NUL ''&& del /f "%s"' % (file, file))register(WindowsViewer)elif sys.platform == "darwin":class MacViewer(Viewer):format = "PNG"options = {'compress_level': 1}def get_command(self, file, **options):# on darwin open returns immediately resulting in the temp# file removal while app is openingcommand = "open -a /Applications/Preview.app"command = "(%s %s; sleep 20; rm -f %s)&" % (command, quote(file),quote(file))return commandregister(MacViewer)else:# unixoidsdef which(executable):path = os.environ.get("PATH")if not path:return Nonefor dirname in path.split(os.pathsep):filename = os.path.join(dirname, executable)if os.path.isfile(filename) and os.access(filename, os.X_OK):return filenamereturn Noneclass UnixViewer(Viewer):format = "PNG"options = {'compress_level': 1}def show_file(self, file, **options):command, executable = self.get_command_ex(file, **options)command = "(%s %s; rm -f %s)&" % (command, quote(file),quote(file))os.system(command)return 1# implementationsclass DisplayViewer(UnixViewer):def get_command_ex(self, file, **options):command = executable = "display"return command, executableif which("display"):register(DisplayViewer)class EogViewer(UnixViewer):def get_command_ex(self, file, **options):command = executable = "eog"return command, executableif which("eog"):register(EogViewer)class XVViewer(UnixViewer):def get_command_ex(self, file, title=None, **options):# note: xv is pretty outdated. most modern systems have# imagemagick's display command instead.command = executable = "xv"if title:command += " -name %s" % quote(title)return command, executableif which("xv"):register(XVViewer)if __name__ == "__main__":if len(sys.argv) < 2:print("Syntax: python ImageShow.py imagefile [title]")sys.exit()print(show(Image.open(sys.argv[1]), *sys.argv[2:]))
123version https://git-lfs.github.com/spec/v1oid sha256:524430596dc905f93b1ed19d51fdc4c993b21c636e869d5334e5268178320744size 3848123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148## The Python Imaging Library.# $Id$## global image statistics## History:# 1996-04-05 fl Created# 1997-05-21 fl Added mask; added rms, var, stddev attributes# 1997-08-05 fl Added median# 1998-07-05 hk Fixed integer overflow error## Notes:# This class shows how to implement delayed evaluation of attributes.# To get a certain value, simply access the corresponding attribute.# The __getattr__ dispatcher takes care of the rest.## Copyright (c) Secret Labs AB 1997.# Copyright (c) Fredrik Lundh 1996-97.## See the README file for information on usage and redistribution.#import mathimport operatorimport functoolsclass Stat(object):def __init__(self, image_or_list, mask=None):try:if mask:self.h = image_or_list.histogram(mask)else:self.h = image_or_list.histogram()except AttributeError:self.h = image_or_list # assume it to be a histogram listif not isinstance(self.h, list):raise TypeError("first argument must be image or list")self.bands = list(range(len(self.h) // 256))def __getattr__(self, id):"Calculate missing attribute"if id[:4] == "_get":raise AttributeError(id)# calculate missing attributev = getattr(self, "_get" + id)()setattr(self, id, v)return vdef _getextrema(self):"Get min/max values for each band in the image"def minmax(histogram):n = 255x = 0for i in range(256):if histogram[i]:n = min(n, i)x = max(x, i)return n, x # returns (255, 0) if there's no data in the histogramv = []for i in range(0, len(self.h), 256):v.append(minmax(self.h[i:]))return vdef _getcount(self):"Get total number of pixels in each layer"v = []for i in range(0, len(self.h), 256):v.append(functools.reduce(operator.add, self.h[i:i+256]))return vdef _getsum(self):"Get sum of all pixels in each layer"v = []for i in range(0, len(self.h), 256):layerSum = 0.0for j in range(256):layerSum += j * self.h[i + j]v.append(layerSum)return vdef _getsum2(self):"Get squared sum of all pixels in each layer"v = []for i in range(0, len(self.h), 256):sum2 = 0.0for j in range(256):sum2 += (j ** 2) * float(self.h[i + j])v.append(sum2)return vdef _getmean(self):"Get average pixel level for each layer"v = []for i in self.bands:v.append(self.sum[i] / self.count[i])return vdef _getmedian(self):"Get median pixel level for each layer"v = []for i in self.bands:s = 0l = self.count[i]//2b = i * 256for j in range(256):s = s + self.h[b+j]if s > l:breakv.append(j)return vdef _getrms(self):"Get RMS for each layer"v = []for i in self.bands:v.append(math.sqrt(self.sum2[i] / self.count[i]))return vdef _getvar(self):"Get variance for each layer"v = []for i in self.bands:n = self.count[i]v.append((self.sum2[i]-(self.sum[i]**2.0)/n)/n)return vdef _getstddev(self):"Get standard deviation for each layer"v = []for i in self.bands:v.append(math.sqrt(self.var[i]))return vGlobal = Stat # compatibility
123version https://git-lfs.github.com/spec/v1oid sha256:9965afb1e384ed7ecf5bebfaad9a142b8bd9d0b76e659e078c4a673cf9a20f1dsize 9360123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303## The Python Imaging Library.# $Id$## a Tk display interface## History:# 96-04-08 fl Created# 96-09-06 fl Added getimage method# 96-11-01 fl Rewritten, removed image attribute and crop method# 97-05-09 fl Use PyImagingPaste method instead of image type# 97-05-12 fl Minor tweaks to match the IFUNC95 interface# 97-05-17 fl Support the "pilbitmap" booster patch# 97-06-05 fl Added file= and data= argument to image constructors# 98-03-09 fl Added width and height methods to Image classes# 98-07-02 fl Use default mode for "P" images without palette attribute# 98-07-02 fl Explicitly destroy Tkinter image objects# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)# 99-07-26 fl Automatically hook into Tkinter (if possible)# 99-08-15 fl Hook uses _imagingtk instead of _imaging## Copyright (c) 1997-1999 by Secret Labs AB# Copyright (c) 1996-1997 by Fredrik Lundh## See the README file for information on usage and redistribution.#import sysif sys.version_info.major > 2:import tkinterelse:import Tkinter as tkinter# required for pypy, which always has cffi installedtry:from cffi import FFIffi = FFI()except ImportError:passfrom . import Imagefrom io import BytesIO# --------------------------------------------------------------------# Check for Tkinter interface hooks_pilbitmap_ok = Nonedef _pilbitmap_check():global _pilbitmap_okif _pilbitmap_ok is None:try:im = Image.new("1", (1, 1))tkinter.BitmapImage(data="PIL:%d" % im.im.id)_pilbitmap_ok = 1except tkinter.TclError:_pilbitmap_ok = 0return _pilbitmap_okdef _get_image_from_kw(kw):source = Noneif "file" in kw:source = kw.pop("file")elif "data" in kw:source = BytesIO(kw.pop("data"))if source:return Image.open(source)# --------------------------------------------------------------------# PhotoImageclass PhotoImage(object):"""A Tkinter-compatible photo image. This can be usedeverywhere Tkinter expects an image object. If the image is an RGBAimage, pixels having alpha 0 are treated as transparent.The constructor takes either a PIL image, or a mode and a size.Alternatively, you can use the **file** or **data** options to initializethe photo image object.:param image: Either a PIL image, or a mode string. If a mode string isused, a size must also be given.:param size: If the first argument is a mode string, this defines the sizeof the image.:keyword file: A filename to load the image from (using``Image.open(file)``).:keyword data: An 8-bit string containing image data (as loaded from animage file)."""def __init__(self, image=None, size=None, **kw):# Tk compatibility: file or dataif image is None:image = _get_image_from_kw(kw)if hasattr(image, "mode") and hasattr(image, "size"):# got an image instead of a modemode = image.modeif mode == "P":# palette mapped dataimage.load()try:mode = image.palette.modeexcept AttributeError:mode = "RGB" # defaultsize = image.sizekw["width"], kw["height"] = sizeelse:mode = imageimage = Noneif mode not in ["1", "L", "RGB", "RGBA"]:mode = Image.getmodebase(mode)self.__mode = modeself.__size = sizeself.__photo = tkinter.PhotoImage(**kw)self.tk = self.__photo.tkif image:self.paste(image)def __del__(self):name = self.__photo.nameself.__photo.name = Nonetry:self.__photo.tk.call("image", "delete", name)except:pass # ignore internal errorsdef __str__(self):"""Get the Tkinter photo image identifier. This method is automaticallycalled by Tkinter whenever a PhotoImage object is passed to a Tkintermethod.:return: A Tkinter photo image identifier (a string)."""return str(self.__photo)def width(self):"""Get the width of the image.:return: The width, in pixels."""return self.__size[0]def height(self):"""Get the height of the image.:return: The height, in pixels."""return self.__size[1]def paste(self, im, box=None):"""Paste a PIL image into the photo image. Note that this canbe very slow if the photo image is displayed.:param im: A PIL image. The size must match the target region. If themode does not match, the image is converted to the mode ofthe bitmap image.:param box: A 4-tuple defining the left, upper, right, and lower pixelcoordinate. See :ref:`coordinate-system`. If None is giveninstead of a tuple, all of the image is assumed."""# convert to blittableim.load()image = im.imif image.isblock() and im.mode == self.__mode:block = imageelse:block = image.new_block(self.__mode, im.size)image.convert2(block, image) # convert directly between bufferstk = self.__photo.tktry:tk.call("PyImagingPhoto", self.__photo, block.id)except tkinter.TclError:# activate Tkinter hooktry:from . import _imagingtktry:if hasattr(tk, 'interp'):# Pypy is using a ffi cdata element# (Pdb) self.tk.interp# <cdata 'Tcl_Interp *' 0x3061b50>_imagingtk.tkinit(int(ffi.cast("uintptr_t", tk.interp)), 1)else:_imagingtk.tkinit(tk.interpaddr(), 1)except AttributeError:_imagingtk.tkinit(id(tk), 0)tk.call("PyImagingPhoto", self.__photo, block.id)except (ImportError, AttributeError, tkinter.TclError):raise # configuration problem; cannot attach to Tkinter# --------------------------------------------------------------------# BitmapImageclass BitmapImage(object):"""A Tkinter-compatible bitmap image. This can be used everywhere Tkinterexpects an image object.The given image must have mode "1". Pixels having value 0 are treated astransparent. Options, if any, are passed on to Tkinter. The most commonlyused option is **foreground**, which is used to specify the color for thenon-transparent parts. See the Tkinter documentation for information onhow to specify colours.:param image: A PIL image."""def __init__(self, image=None, **kw):# Tk compatibility: file or dataif image is None:image = _get_image_from_kw(kw)self.__mode = image.modeself.__size = image.sizeif _pilbitmap_check():# fast way (requires the pilbitmap booster patch)image.load()kw["data"] = "PIL:%d" % image.im.idself.__im = image # must keep a referenceelse:# slow but safe waykw["data"] = image.tobitmap()self.__photo = tkinter.BitmapImage(**kw)def __del__(self):name = self.__photo.nameself.__photo.name = Nonetry:self.__photo.tk.call("image", "delete", name)except:pass # ignore internal errorsdef width(self):"""Get the width of the image.:return: The width, in pixels."""return self.__size[0]def height(self):"""Get the height of the image.:return: The height, in pixels."""return self.__size[1]def __str__(self):"""Get the Tkinter bitmap image identifier. This method is automaticallycalled by Tkinter whenever a BitmapImage object is passed to a Tkintermethod.:return: A Tkinter bitmap image identifier (a string)."""return str(self.__photo)def getimage(photo):""" This function is unimplemented """"""Copies the contents of a PhotoImage to a PIL image memory."""photo.tk.call("PyImagingPhotoGet", photo)def _show(image, title):"""Helper for the Image.show method."""class UI(tkinter.Label):def __init__(self, master, im):if im.mode == "1":self.image = BitmapImage(im, foreground="white", master=master)else:self.image = PhotoImage(im, master=master)tkinter.Label.__init__(self, master, image=self.image,bg="black", bd=0)if not tkinter._default_root:raise IOError("tkinter not initialized")top = tkinter.Toplevel()if title:top.title(title)UI(top, image).pack()
123version https://git-lfs.github.com/spec/v1oid sha256:ded4a7467ef8eea68d0bef0168e0b44f50b278c26868a533a4b13008f2b21c5bsize 28391234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798## The Python Imaging Library.# $Id$## transform wrappers## History:# 2002-04-08 fl Created## Copyright (c) 2002 by Secret Labs AB# Copyright (c) 2002 by Fredrik Lundh## See the README file for information on usage and redistribution.#from . import Imageclass Transform(Image.ImageTransformHandler):def __init__(self, data):self.data = datadef getdata(self):return self.method, self.datadef transform(self, size, image, **options):# can be overriddenmethod, data = self.getdata()return image.transform(size, method, data, **options)class AffineTransform(Transform):"""Define an affine image transform.This function takes a 6-tuple (a, b, c, d, e, f) which contain the firsttwo rows from an affine transform matrix. For each pixel (x, y) in theoutput image, the new value is taken from a position (a x + b y + c,d x + e y + f) in the input image, rounded to nearest pixel.This function can be used to scale, translate, rotate, and shear theoriginal image.See :py:meth:`~PIL.Image.Image.transform`:param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rowsfrom an affine transform matrix."""method = Image.AFFINEclass ExtentTransform(Transform):"""Define a transform to extract a subregion from an image.Maps a rectangle (defined by two corners) from the image to a rectangle ofthe given size. The resulting image will contain data sampled from betweenthe corners, such that (x0, y0) in the input image will end up at (0,0) inthe output image, and (x1, y1) at size.This method can be used to crop, stretch, shrink, or mirror an arbitraryrectangle in the current image. It is slightly slower than crop, but aboutas fast as a corresponding resize operation.See :py:meth:`~PIL.Image.Image.transform`:param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in theinput image's coordinate system. See :ref:`coordinate-system`."""method = Image.EXTENTclass QuadTransform(Transform):"""Define a quad image transform.Maps a quadrilateral (a region defined by four corners) from the image to arectangle of the given size.See :py:meth:`~PIL.Image.Image.transform`:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain theupper left, lower left, lower right, and upper right corner of thesource quadrilateral."""method = Image.QUADclass MeshTransform(Transform):"""Define a mesh image transform. A mesh transform consists of one or moreindividual quad transforms.See :py:meth:`~PIL.Image.Image.transform`:param data: A list of (bbox, quad) tuples."""method = Image.MESH
123version https://git-lfs.github.com/spec/v1oid sha256:707e9b06b5b2938d9ca29bc27cf20b621a5391d9e0c40d5df2fd52ed1f6897e6size 7217123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228## The Python Imaging Library.# $Id$## a Windows DIB display interface## History:# 1996-05-20 fl Created# 1996-09-20 fl Fixed subregion exposure# 1997-09-21 fl Added draw primitive (for tzPrint)# 2003-05-21 fl Added experimental Window/ImageWindow classes# 2003-09-05 fl Added fromstring/tostring methods## Copyright (c) Secret Labs AB 1997-2003.# Copyright (c) Fredrik Lundh 1996-2003.## See the README file for information on usage and redistribution.#from . import Imageclass HDC(object):"""Wraps an HDC integer. The resulting object can be passed to the:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`methods."""def __init__(self, dc):self.dc = dcdef __int__(self):return self.dcclass HWND(object):"""Wraps an HWND integer. The resulting object can be passed to the:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`methods, instead of a DC."""def __init__(self, wnd):self.wnd = wnddef __int__(self):return self.wndclass Dib(object):"""A Windows bitmap with the given mode and size. The mode can be one of "1","L", "P", or "RGB".If the display requires a palette, this constructor creates a suitablepalette and associates it with the image. For an "L" image, 128 greylevelsare allocated. For an "RGB" image, a 6x6x6 colour cube is used, togetherwith 20 greylevels.To make sure that palettes work properly under Windows, you must call the**palette** method upon certain events from Windows.:param image: Either a PIL image, or a mode string. If a mode string isused, a size must also be given. The mode can be one of "1","L", "P", or "RGB".:param size: If the first argument is a mode string, thisdefines the size of the image."""def __init__(self, image, size=None):if hasattr(image, "mode") and hasattr(image, "size"):mode = image.modesize = image.sizeelse:mode = imageimage = Noneif mode not in ["1", "L", "P", "RGB"]:mode = Image.getmodebase(mode)self.image = Image.core.display(mode, size)self.mode = modeself.size = sizeif image:self.paste(image)def expose(self, handle):"""Copy the bitmap contents to a device context.:param handle: Device context (HDC), cast to a Python integer, or anHDC or HWND instance. In PythonWin, you can use the:py:meth:`CDC.GetHandleAttrib` to get a suitable handle."""if isinstance(handle, HWND):dc = self.image.getdc(handle)try:result = self.image.expose(dc)finally:self.image.releasedc(handle, dc)else:result = self.image.expose(handle)return resultdef draw(self, handle, dst, src=None):"""Same as expose, but allows you to specify where to draw the image, andwhat part of it to draw.The destination and source areas are given as 4-tuple rectangles. Ifthe source is omitted, the entire image is copied. If the source andthe destination have different sizes, the image is resized asnecessary."""if not src:src = (0, 0) + self.sizeif isinstance(handle, HWND):dc = self.image.getdc(handle)try:result = self.image.draw(dc, dst, src)finally:self.image.releasedc(handle, dc)else:result = self.image.draw(handle, dst, src)return resultdef query_palette(self, handle):"""Installs the palette associated with the image in the given devicecontext.This method should be called upon **QUERYNEWPALETTE** and**PALETTECHANGED** events from Windows. If this method returns anon-zero value, one or more display palette entries were changed, andthe image should be redrawn.:param handle: Device context (HDC), cast to a Python integer, or anHDC or HWND instance.:return: A true value if one or more entries were changed (thisindicates that the image should be redrawn)."""if isinstance(handle, HWND):handle = self.image.getdc(handle)try:result = self.image.query_palette(handle)finally:self.image.releasedc(handle, handle)else:result = self.image.query_palette(handle)return resultdef paste(self, im, box=None):"""Paste a PIL image into the bitmap image.:param im: A PIL image. The size must match the target region.If the mode does not match, the image is converted to themode of the bitmap image.:param box: A 4-tuple defining the left, upper, right, andlower pixel coordinate. See :ref:`coordinate-system`. IfNone is given instead of a tuple, all of the image isassumed."""im.load()if self.mode != im.mode:im = im.convert(self.mode)if box:self.image.paste(im.im, box)else:self.image.paste(im.im)def frombytes(self, buffer):"""Load display memory contents from byte data.:param buffer: A buffer containing display data (usuallydata returned from <b>tobytes</b>)"""return self.image.frombytes(buffer)def tobytes(self):"""Copy display memory contents to bytes object.:return: A bytes object containing display data."""return self.image.tobytes()class Window(object):"""Create a Window with the given title size."""def __init__(self, title="PIL", width=None, height=None):self.hwnd = Image.core.createwindow(title, self.__dispatcher, width or 0, height or 0)def __dispatcher(self, action, *args):return getattr(self, "ui_handle_" + action)(*args)def ui_handle_clear(self, dc, x0, y0, x1, y1):passdef ui_handle_damage(self, x0, y0, x1, y1):passdef ui_handle_destroy(self):passdef ui_handle_repair(self, dc, x0, y0, x1, y1):passdef ui_handle_resize(self, width, height):passdef mainloop(self):Image.core.eventloop()class ImageWindow(Window):"""Create an image window which displays the given image."""def __init__(self, image, title="PIL"):if not isinstance(image, Dib):image = Dib(image)self.image = imagewidth, height = image.sizeWindow.__init__(self, title, width=width, height=height)def ui_handle_repair(self, dc, x0, y0, x1, y1):self.image.draw(dc, (x0, y0, x1, y1))
123version https://git-lfs.github.com/spec/v1oid sha256:5835d995d702262074f9dc23cdd99c8f3d899111416a3e1044e5878ff918dd88size 22401234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495## The Python Imaging Library.# $Id$## IM Tools support for PIL## history:# 1996-05-27 fl Created (read 8-bit images only)# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)## Copyright (c) Secret Labs AB 1997-2001.# Copyright (c) Fredrik Lundh 1996-2001.## See the README file for information on usage and redistribution.#import refrom . import Image, ImageFile__version__ = "0.2"## --------------------------------------------------------------------field = re.compile(br"([a-z]*) ([^ \r\n]*)")### Image plugin for IM Tools images.class ImtImageFile(ImageFile.ImageFile):format = "IMT"format_description = "IM Tools"def _open(self):# Quick rejection: if there's not a LF among the first# 100 bytes, this is (probably) not a text header.if b"\n" not in self.fp.read(100):raise SyntaxError("not an IM file")self.fp.seek(0)xsize = ysize = 0while True:s = self.fp.read(1)if not s:breakif s == b'\x0C':# image data beginsself.tile = [("raw", (0, 0)+self.size,self.fp.tell(),(self.mode, 0, 1))]breakelse:# read key/value pair# FIXME: dangerous, may read whole files = s + self.fp.readline()if len(s) == 1 or len(s) > 100:breakif s[0] == ord(b"*"):continue # commentm = field.match(s)if not m:breakk, v = m.group(1, 2)if k == "width":xsize = int(v)self.size = xsize, ysizeelif k == "height":ysize = int(v)self.size = xsize, ysizeelif k == "pixel" and v == "n8":self.mode = "L"## --------------------------------------------------------------------Image.register_open(ImtImageFile.format, ImtImageFile)## no extension registered (".im" is simply too common)
Proteus 8 Professional/Tools/Python/Lib/PIL/BdfFontFile.py+133-3
Proteus 8 Professional/Tools/Python/Lib/PIL/BlpImagePlugin.py+435-3
Proteus 8 Professional/Tools/Python/Lib/PIL/BmpImagePlugin.py+289-3
Proteus 8 Professional/Tools/Python/Lib/PIL/BufrStubImagePlugin.py+72-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ContainerIO.py+116-3
Proteus 8 Professional/Tools/Python/Lib/PIL/CurImagePlugin.py+86-3
Proteus 8 Professional/Tools/Python/Lib/PIL/DcxImagePlugin.py+87-3
Proteus 8 Professional/Tools/Python/Lib/PIL/DdsImagePlugin.py+172-3
Proteus 8 Professional/Tools/Python/Lib/PIL/EpsImagePlugin.py+429-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ExifTags.py+315-3
Proteus 8 Professional/Tools/Python/Lib/PIL/FitsStubImagePlugin.py+75-3
Proteus 8 Professional/Tools/Python/Lib/PIL/FliImagePlugin.py+163-3
Proteus 8 Professional/Tools/Python/Lib/PIL/FontFile.py+114-3
Proteus 8 Professional/Tools/Python/Lib/PIL/FpxImagePlugin.py+229-3
Proteus 8 Professional/Tools/Python/Lib/PIL/FtexImagePlugin.py+94-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GbrImagePlugin.py+94-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GdImageFile.py+83-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GifImagePlugin.py+814-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GimpGradientFile.py+138-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GimpPaletteFile.py+62-3
Proteus 8 Professional/Tools/Python/Lib/PIL/GribStubImagePlugin.py+73-3
Proteus 8 Professional/Tools/Python/Lib/PIL/Hdf5StubImagePlugin.py+72-3
Proteus 8 Professional/Tools/Python/Lib/PIL/IcnsImagePlugin.py+374-3
Proteus 8 Professional/Tools/Python/Lib/PIL/IcoImagePlugin.py+284-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImImagePlugin.py+347-3
Proteus 8 Professional/Tools/Python/Lib/PIL/Image.py+2930-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageChops.py+283-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageCms.py+955-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageColor.py+309-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageDraw.py+387-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageDraw2.py+108-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageEnhance.py+100-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFile.py+667-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFilter.py+486-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageFont.py+471-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageGrab.py+80-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMath.py+271-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMode.py+55-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageMorph.py+250-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageOps.py+529-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImagePalette.py+216-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImagePath.py+20-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageQt.py+212-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageSequence.py+56-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageShow.py+194-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageStat.py+148-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageTk.py+303-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageTransform.py+98-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImageWin.py+228-3
Proteus 8 Professional/Tools/Python/Lib/PIL/ImtImagePlugin.py+95-3