content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
#\n# The Python Imaging Library.\n# $Id$\n#\n# image enhancement classes\n#\n# For a background, see "Image Processing By Interpolation and\n# Extrapolation", Paul Haeberli and Douglas Voorhies. Available\n# at http://www.graficaobscura.com/interp/index.html\n#\n# History:\n# 1996-03-23 fl Created\n# 2009-06-16 fl Fixed mean calculation\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFilter, ImageStat\n\n\nclass _Enhance:\n image: Image.Image\n degenerate: Image.Image\n\n def enhance(self, factor: float) -> Image.Image:\n """\n Returns an enhanced image.\n\n :param factor: A floating point value controlling the enhancement.\n Factor 1.0 always returns a copy of the original image,\n lower factors mean less color (brightness, contrast,\n etc), and higher values more. There are no restrictions\n on this value.\n :rtype: :py:class:`~PIL.Image.Image`\n """\n return Image.blend(self.degenerate, self.image, factor)\n\n\nclass Color(_Enhance):\n """Adjust image color balance.\n\n This class can be used to adjust the colour balance of an image, in\n a manner similar to the controls on a colour TV set. An enhancement\n factor of 0.0 gives a black and white image. A factor of 1.0 gives\n the original image.\n """\n\n def __init__(self, image: Image.Image) -> None:\n self.image = image\n self.intermediate_mode = "L"\n if "A" in image.getbands():\n self.intermediate_mode = "LA"\n\n if self.intermediate_mode != image.mode:\n image = image.convert(self.intermediate_mode).convert(image.mode)\n self.degenerate = image\n\n\nclass Contrast(_Enhance):\n """Adjust image contrast.\n\n This class can be used to control the contrast of an image, similar\n to the contrast control on a TV set. An enhancement factor of 0.0\n gives a solid gray image. A factor of 1.0 gives the original image.\n """\n\n def __init__(self, image: Image.Image) -> None:\n self.image = image\n if image.mode != "L":\n image = image.convert("L")\n mean = int(ImageStat.Stat(image).mean[0] + 0.5)\n self.degenerate = Image.new("L", image.size, mean)\n if self.degenerate.mode != self.image.mode:\n self.degenerate = self.degenerate.convert(self.image.mode)\n\n if "A" in self.image.getbands():\n self.degenerate.putalpha(self.image.getchannel("A"))\n\n\nclass Brightness(_Enhance):\n """Adjust image brightness.\n\n This class can be used to control the brightness of an image. An\n enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the\n original image.\n """\n\n def __init__(self, image: Image.Image) -> None:\n self.image = image\n self.degenerate = Image.new(image.mode, image.size, 0)\n\n if "A" in image.getbands():\n self.degenerate.putalpha(image.getchannel("A"))\n\n\nclass Sharpness(_Enhance):\n """Adjust image sharpness.\n\n This class can be used to adjust the sharpness of an image. An\n enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the\n original image, and a factor of 2.0 gives a sharpened image.\n """\n\n def __init__(self, image: Image.Image) -> None:\n self.image = image\n self.degenerate = image.filter(ImageFilter.SMOOTH)\n\n if "A" in image.getbands():\n self.degenerate.putalpha(image.getchannel("A"))\n | .venv\Lib\site-packages\PIL\ImageEnhance.py | ImageEnhance.py | Python | 3,740 | 0.95 | 0.20354 | 0.215909 | python-kit | 584 | 2024-12-14T20:28:24.185372 | MIT | false | 39d28fbecaa186860ad5be044cc65103 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# base class for image file handlers\n#\n# history:\n# 1995-09-09 fl Created\n# 1996-03-11 fl Fixed load mechanism.\n# 1996-04-15 fl Added pcx/xbm decoders.\n# 1996-04-30 fl Added encoders.\n# 1996-12-14 fl Added load helpers\n# 1997-01-11 fl Use encode_to_file where possible\n# 1997-08-27 fl Flush output in _save\n# 1998-03-05 fl Use memory mapping for some modes\n# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"\n# 1999-05-31 fl Added image parser\n# 2000-10-12 fl Set readonly flag on memory-mapped images\n# 2002-03-20 fl Use better messages for common decoder errors\n# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available\n# 2003-10-30 fl Added StubImageFile class\n# 2004-02-25 fl Made incremental parser more robust\n#\n# Copyright (c) 1997-2004 by Secret Labs AB\n# Copyright (c) 1995-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport abc\nimport io\nimport itertools\nimport logging\nimport os\nimport struct\nfrom typing import IO, Any, NamedTuple, cast\n\nfrom . import ExifTags, Image\nfrom ._deprecate import deprecate\nfrom ._util import DeferredError, is_path\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from ._typing import StrOrBytesPath\n\nlogger = logging.getLogger(__name__)\n\nMAXBLOCK = 65536\n\nSAFEBLOCK = 1024 * 1024\n\nLOAD_TRUNCATED_IMAGES = False\n"""Whether or not to load truncated image files. User code may change this."""\n\nERRORS = {\n -1: "image buffer overrun error",\n -2: "decoding error",\n -3: "unknown error",\n -8: "bad configuration",\n -9: "out of memory error",\n}\n"""\nDict of known error codes returned from :meth:`.PyDecoder.decode`,\n:meth:`.PyEncoder.encode` :meth:`.PyEncoder.encode_to_pyfd` and\n:meth:`.PyEncoder.encode_to_file`.\n"""\n\n\n#\n# --------------------------------------------------------------------\n# Helpers\n\n\ndef _get_oserror(error: int, *, encoder: bool) -> OSError:\n try:\n msg = Image.core.getcodecstatus(error)\n except AttributeError:\n msg = ERRORS.get(error)\n if not msg:\n msg = f"{'encoder' if encoder else 'decoder'} error {error}"\n msg += f" when {'writing' if encoder else 'reading'} image file"\n return OSError(msg)\n\n\ndef raise_oserror(error: int) -> OSError:\n deprecate(\n "raise_oserror",\n 12,\n action="It is only useful for translating error codes returned by a codec's "\n "decode() method, which ImageFile already does automatically.",\n )\n raise _get_oserror(error, encoder=False)\n\n\ndef _tilesort(t: _Tile) -> int:\n # sort on offset\n return t[2]\n\n\nclass _Tile(NamedTuple):\n codec_name: str\n extents: tuple[int, int, int, int] | None\n offset: int = 0\n args: tuple[Any, ...] | str | None = None\n\n\n#\n# --------------------------------------------------------------------\n# ImageFile base class\n\n\nclass ImageFile(Image.Image):\n """Base class for image file format handlers."""\n\n def __init__(\n self, fp: StrOrBytesPath | IO[bytes], filename: str | bytes | None = None\n ) -> None:\n super().__init__()\n\n self._min_frame = 0\n\n self.custom_mimetype: str | None = None\n\n self.tile: list[_Tile] = []\n """ A list of tile descriptors """\n\n self.readonly = 1 # until we know better\n\n self.decoderconfig: tuple[Any, ...] = ()\n self.decodermaxblock = MAXBLOCK\n\n if is_path(fp):\n # filename\n self.fp = open(fp, "rb")\n self.filename = os.fspath(fp)\n self._exclusive_fp = True\n else:\n # stream\n self.fp = cast(IO[bytes], fp)\n self.filename = filename if filename is not None else ""\n # can be overridden\n self._exclusive_fp = False\n\n try:\n try:\n self._open()\n except (\n IndexError, # end of data\n TypeError, # end of data (ord)\n KeyError, # unsupported mode\n EOFError, # got header but not the first frame\n struct.error,\n ) as v:\n raise SyntaxError(v) from v\n\n if not self.mode or self.size[0] <= 0 or self.size[1] <= 0:\n msg = "not identified by this driver"\n raise SyntaxError(msg)\n except BaseException:\n # close the file only if we have opened it this constructor\n if self._exclusive_fp:\n self.fp.close()\n raise\n\n def _open(self) -> None:\n pass\n\n def _close_fp(self):\n if getattr(self, "_fp", False) and not isinstance(self._fp, DeferredError):\n if self._fp != self.fp:\n self._fp.close()\n self._fp = DeferredError(ValueError("Operation on closed image"))\n if self.fp:\n self.fp.close()\n\n def close(self) -> None:\n """\n Closes the file pointer, if possible.\n\n This operation will destroy the image core and release its memory.\n The image data will be unusable afterward.\n\n This function is required to close images that have multiple frames or\n have not had their file read and closed by the\n :py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for\n more information.\n """\n try:\n self._close_fp()\n self.fp = None\n except Exception as msg:\n logger.debug("Error closing: %s", msg)\n\n super().close()\n\n def get_child_images(self) -> list[ImageFile]:\n child_images = []\n exif = self.getexif()\n ifds = []\n if ExifTags.Base.SubIFDs in exif:\n subifd_offsets = exif[ExifTags.Base.SubIFDs]\n if subifd_offsets:\n if not isinstance(subifd_offsets, tuple):\n subifd_offsets = (subifd_offsets,)\n for subifd_offset in subifd_offsets:\n ifds.append((exif._get_ifd_dict(subifd_offset), subifd_offset))\n ifd1 = exif.get_ifd(ExifTags.IFD.IFD1)\n if ifd1 and ifd1.get(ExifTags.Base.JpegIFOffset):\n assert exif._info is not None\n ifds.append((ifd1, exif._info.next))\n\n offset = None\n for ifd, ifd_offset in ifds:\n assert self.fp is not None\n current_offset = self.fp.tell()\n if offset is None:\n offset = current_offset\n\n fp = self.fp\n if ifd is not None:\n thumbnail_offset = ifd.get(ExifTags.Base.JpegIFOffset)\n if thumbnail_offset is not None:\n thumbnail_offset += getattr(self, "_exif_offset", 0)\n self.fp.seek(thumbnail_offset)\n\n length = ifd.get(ExifTags.Base.JpegIFByteCount)\n assert isinstance(length, int)\n data = self.fp.read(length)\n fp = io.BytesIO(data)\n\n with Image.open(fp) as im:\n from . import TiffImagePlugin\n\n if thumbnail_offset is None and isinstance(\n im, TiffImagePlugin.TiffImageFile\n ):\n im._frame_pos = [ifd_offset]\n im._seek(0)\n im.load()\n child_images.append(im)\n\n if offset is not None:\n assert self.fp is not None\n self.fp.seek(offset)\n return child_images\n\n def get_format_mimetype(self) -> str | None:\n if self.custom_mimetype:\n return self.custom_mimetype\n if self.format is not None:\n return Image.MIME.get(self.format.upper())\n return None\n\n def __getstate__(self) -> list[Any]:\n return super().__getstate__() + [self.filename]\n\n def __setstate__(self, state: list[Any]) -> None:\n self.tile = []\n if len(state) > 5:\n self.filename = state[5]\n super().__setstate__(state)\n\n def verify(self) -> None:\n """Check file integrity"""\n\n # raise exception if something's wrong. must be called\n # directly after open, and closes file when finished.\n if self._exclusive_fp:\n self.fp.close()\n self.fp = None\n\n def load(self) -> Image.core.PixelAccess | None:\n """Load image data based on tile list"""\n\n if not self.tile and self._im is None:\n msg = "cannot load this image"\n raise OSError(msg)\n\n pixel = Image.Image.load(self)\n if not self.tile:\n return pixel\n\n self.map: mmap.mmap | None = None\n use_mmap = self.filename and len(self.tile) == 1\n\n readonly = 0\n\n # look for read/seek overrides\n if hasattr(self, "load_read"):\n read = self.load_read\n # don't use mmap if there are custom read/seek functions\n use_mmap = False\n else:\n read = self.fp.read\n\n if hasattr(self, "load_seek"):\n seek = self.load_seek\n use_mmap = False\n else:\n seek = self.fp.seek\n\n if use_mmap:\n # try memory mapping\n decoder_name, extents, offset, args = self.tile[0]\n if isinstance(args, str):\n args = (args, 0, 1)\n if (\n decoder_name == "raw"\n and isinstance(args, tuple)\n and len(args) >= 3\n and args[0] == self.mode\n and args[0] in Image._MAPMODES\n ):\n try:\n # use mmap, if possible\n import mmap\n\n with open(self.filename) as fp:\n self.map = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)\n if offset + self.size[1] * args[1] > self.map.size():\n msg = "buffer is not large enough"\n raise OSError(msg)\n self.im = Image.core.map_buffer(\n self.map, self.size, decoder_name, offset, args\n )\n readonly = 1\n # After trashing self.im,\n # we might need to reload the palette data.\n if self.palette:\n self.palette.dirty = 1\n except (AttributeError, OSError, ImportError):\n self.map = None\n\n self.load_prepare()\n err_code = -3 # initialize to unknown error\n if not self.map:\n # sort tiles in file order\n self.tile.sort(key=_tilesort)\n\n # FIXME: This is a hack to handle TIFF's JpegTables tag.\n prefix = getattr(self, "tile_prefix", b"")\n\n # Remove consecutive duplicates that only differ by their offset\n self.tile = [\n list(tiles)[-1]\n for _, tiles in itertools.groupby(\n self.tile, lambda tile: (tile[0], tile[1], tile[3])\n )\n ]\n for i, (decoder_name, extents, offset, args) in enumerate(self.tile):\n seek(offset)\n decoder = Image._getdecoder(\n self.mode, decoder_name, args, self.decoderconfig\n )\n try:\n decoder.setimage(self.im, extents)\n if decoder.pulls_fd:\n decoder.setfd(self.fp)\n err_code = decoder.decode(b"")[1]\n else:\n b = prefix\n while True:\n read_bytes = self.decodermaxblock\n if i + 1 < len(self.tile):\n next_offset = self.tile[i + 1].offset\n if next_offset > offset:\n read_bytes = next_offset - offset\n try:\n s = read(read_bytes)\n except (IndexError, struct.error) as e:\n # truncated png/gif\n if LOAD_TRUNCATED_IMAGES:\n break\n else:\n msg = "image file is truncated"\n raise OSError(msg) from e\n\n if not s: # truncated jpeg\n if LOAD_TRUNCATED_IMAGES:\n break\n else:\n msg = (\n "image file is truncated "\n f"({len(b)} bytes not processed)"\n )\n raise OSError(msg)\n\n b = b + s\n n, err_code = decoder.decode(b)\n if n < 0:\n break\n b = b[n:]\n finally:\n # Need to cleanup here to prevent leaks\n decoder.cleanup()\n\n self.tile = []\n self.readonly = readonly\n\n self.load_end()\n\n if self._exclusive_fp and self._close_exclusive_fp_after_loading:\n self.fp.close()\n self.fp = None\n\n if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:\n # still raised if decoder fails to return anything\n raise _get_oserror(err_code, encoder=False)\n\n return Image.Image.load(self)\n\n def load_prepare(self) -> None:\n # create image memory if necessary\n if self._im is None:\n self.im = Image.core.new(self.mode, self.size)\n # create palette (optional)\n if self.mode == "P":\n Image.Image.load(self)\n\n def load_end(self) -> None:\n # may be overridden\n pass\n\n # may be defined for contained formats\n # def load_seek(self, pos: int) -> None:\n # pass\n\n # may be defined for blocked formats (e.g. PNG)\n # def load_read(self, read_bytes: int) -> bytes:\n # pass\n\n def _seek_check(self, frame: int) -> bool:\n if (\n frame < self._min_frame\n # Only check upper limit on frames if additional seek operations\n # are not required to do so\n or (\n not (hasattr(self, "_n_frames") and self._n_frames is None)\n and frame >= getattr(self, "n_frames") + self._min_frame\n )\n ):\n msg = "attempt to seek outside sequence"\n raise EOFError(msg)\n\n return self.tell() != frame\n\n\nclass StubHandler(abc.ABC):\n def open(self, im: StubImageFile) -> None:\n pass\n\n @abc.abstractmethod\n def load(self, im: StubImageFile) -> Image.Image:\n pass\n\n\nclass StubImageFile(ImageFile, metaclass=abc.ABCMeta):\n """\n Base class for stub image loaders.\n\n A stub loader is an image loader that can identify files of a\n certain format, but relies on external code to load the file.\n """\n\n @abc.abstractmethod\n def _open(self) -> None:\n pass\n\n def load(self) -> Image.core.PixelAccess | None:\n loader = self._load()\n if loader is None:\n msg = f"cannot find loader for this {self.format} file"\n raise OSError(msg)\n image = loader.load(self)\n assert image is not None\n # become the other object (!)\n self.__class__ = image.__class__ # type: ignore[assignment]\n self.__dict__ = image.__dict__\n return image.load()\n\n @abc.abstractmethod\n def _load(self) -> StubHandler | None:\n """(Hook) Find actual image loader."""\n pass\n\n\nclass Parser:\n """\n Incremental image parser. This class implements the standard\n feed/close consumer interface.\n """\n\n incremental = None\n image: Image.Image | None = None\n data: bytes | None = None\n decoder: Image.core.ImagingDecoder | PyDecoder | None = None\n offset = 0\n finished = 0\n\n def reset(self) -> None:\n """\n (Consumer) Reset the parser. Note that you can only call this\n method immediately after you've created a parser; parser\n instances cannot be reused.\n """\n assert self.data is None, "cannot reuse parsers"\n\n def feed(self, data: bytes) -> None:\n """\n (Consumer) Feed data to the parser.\n\n :param data: A string buffer.\n :exception OSError: If the parser failed to parse the image file.\n """\n # collect data\n\n if self.finished:\n return\n\n if self.data is None:\n self.data = data\n else:\n self.data = self.data + data\n\n # parse what we have\n if self.decoder:\n if self.offset > 0:\n # skip header\n skip = min(len(self.data), self.offset)\n self.data = self.data[skip:]\n self.offset = self.offset - skip\n if self.offset > 0 or not self.data:\n return\n\n n, e = self.decoder.decode(self.data)\n\n if n < 0:\n # end of stream\n self.data = None\n self.finished = 1\n if e < 0:\n # decoding error\n self.image = None\n raise _get_oserror(e, encoder=False)\n else:\n # end of image\n return\n self.data = self.data[n:]\n\n elif self.image:\n # if we end up here with no decoder, this file cannot\n # be incrementally parsed. wait until we've gotten all\n # available data\n pass\n\n else:\n # attempt to open this file\n try:\n with io.BytesIO(self.data) as fp:\n im = Image.open(fp)\n except OSError:\n pass # not enough data\n else:\n flag = hasattr(im, "load_seek") or hasattr(im, "load_read")\n if flag or len(im.tile) != 1:\n # custom load code, or multiple tiles\n self.decode = None\n else:\n # initialize decoder\n im.load_prepare()\n d, e, o, a = im.tile[0]\n im.tile = []\n self.decoder = Image._getdecoder(im.mode, d, a, im.decoderconfig)\n self.decoder.setimage(im.im, e)\n\n # calculate decoder offset\n self.offset = o\n if self.offset <= len(self.data):\n self.data = self.data[self.offset :]\n self.offset = 0\n\n self.image = im\n\n def __enter__(self) -> Parser:\n return self\n\n def __exit__(self, *args: object) -> None:\n self.close()\n\n def close(self) -> Image.Image:\n """\n (Consumer) Close the stream.\n\n :returns: An image object.\n :exception OSError: If the parser failed to parse the image file either\n because it cannot be identified or cannot be\n decoded.\n """\n # finish decoding\n if self.decoder:\n # get rid of what's left in the buffers\n self.feed(b"")\n self.data = self.decoder = None\n if not self.finished:\n msg = "image was incomplete"\n raise OSError(msg)\n if not self.image:\n msg = "cannot parse this image"\n raise OSError(msg)\n if self.data:\n # incremental parsing not possible; reopen the file\n # not that we have all data\n with io.BytesIO(self.data) as fp:\n try:\n self.image = Image.open(fp)\n finally:\n self.image.load()\n return self.image\n\n\n# --------------------------------------------------------------------\n\n\ndef _save(im: Image.Image, fp: IO[bytes], tile: list[_Tile], bufsize: int = 0) -> None:\n """Helper to save image based on tile list\n\n :param im: Image object.\n :param fp: File object.\n :param tile: Tile list.\n :param bufsize: Optional buffer size\n """\n\n im.load()\n if not hasattr(im, "encoderconfig"):\n im.encoderconfig = ()\n tile.sort(key=_tilesort)\n # FIXME: make MAXBLOCK a configuration parameter\n # It would be great if we could have the encoder specify what it needs\n # But, it would need at least the image size in most cases. RawEncode is\n # a tricky case.\n bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c\n try:\n fh = fp.fileno()\n fp.flush()\n _encode_tile(im, fp, tile, bufsize, fh)\n except (AttributeError, io.UnsupportedOperation) as exc:\n _encode_tile(im, fp, tile, bufsize, None, exc)\n if hasattr(fp, "flush"):\n fp.flush()\n\n\ndef _encode_tile(\n im: Image.Image,\n fp: IO[bytes],\n tile: list[_Tile],\n bufsize: int,\n fh: int | None,\n exc: BaseException | None = None,\n) -> None:\n for encoder_name, extents, offset, args in tile:\n if offset > 0:\n fp.seek(offset)\n encoder = Image._getencoder(im.mode, encoder_name, args, im.encoderconfig)\n try:\n encoder.setimage(im.im, extents)\n if encoder.pushes_fd:\n encoder.setfd(fp)\n errcode = encoder.encode_to_pyfd()[1]\n else:\n if exc:\n # compress to Python file-compatible object\n while True:\n errcode, data = encoder.encode(bufsize)[1:]\n fp.write(data)\n if errcode:\n break\n else:\n # slight speedup: compress to real file object\n assert fh is not None\n errcode = encoder.encode_to_file(fh, bufsize)\n if errcode < 0:\n raise _get_oserror(errcode, encoder=True) from exc\n finally:\n encoder.cleanup()\n\n\ndef _safe_read(fp: IO[bytes], size: int) -> bytes:\n """\n Reads large blocks in a safe way. Unlike fp.read(n), this function\n doesn't trust the user. If the requested size is larger than\n SAFEBLOCK, the file is read block by block.\n\n :param fp: File handle. Must implement a <b>read</b> method.\n :param size: Number of bytes to read.\n :returns: A string containing <i>size</i> bytes of data.\n\n Raises an OSError if the file is truncated and the read cannot be completed\n\n """\n if size <= 0:\n return b""\n if size <= SAFEBLOCK:\n data = fp.read(size)\n if len(data) < size:\n msg = "Truncated File Read"\n raise OSError(msg)\n return data\n blocks: list[bytes] = []\n remaining_size = size\n while remaining_size > 0:\n block = fp.read(min(remaining_size, SAFEBLOCK))\n if not block:\n break\n blocks.append(block)\n remaining_size -= len(block)\n if sum(len(block) for block in blocks) < size:\n msg = "Truncated File Read"\n raise OSError(msg)\n return b"".join(blocks)\n\n\nclass PyCodecState:\n def __init__(self) -> None:\n self.xsize = 0\n self.ysize = 0\n self.xoff = 0\n self.yoff = 0\n\n def extents(self) -> tuple[int, int, int, int]:\n return self.xoff, self.yoff, self.xoff + self.xsize, self.yoff + self.ysize\n\n\nclass PyCodec:\n fd: IO[bytes] | None\n\n def __init__(self, mode: str, *args: Any) -> None:\n self.im: Image.core.ImagingCore | None = None\n self.state = PyCodecState()\n self.fd = None\n self.mode = mode\n self.init(args)\n\n def init(self, args: tuple[Any, ...]) -> None:\n """\n Override to perform codec specific initialization\n\n :param args: Tuple of arg items from the tile entry\n :returns: None\n """\n self.args = args\n\n def cleanup(self) -> None:\n """\n Override to perform codec specific cleanup\n\n :returns: None\n """\n pass\n\n def setfd(self, fd: IO[bytes]) -> None:\n """\n Called from ImageFile to set the Python file-like object\n\n :param fd: A Python file-like object\n :returns: None\n """\n self.fd = fd\n\n def setimage(\n self,\n im: Image.core.ImagingCore,\n extents: tuple[int, int, int, int] | None = None,\n ) -> None:\n """\n Called from ImageFile to set the core output image for the codec\n\n :param im: A core image object\n :param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle\n for this tile\n :returns: None\n """\n\n # following c code\n self.im = im\n\n if extents:\n (x0, y0, x1, y1) = extents\n else:\n (x0, y0, x1, y1) = (0, 0, 0, 0)\n\n if x0 == 0 and x1 == 0:\n self.state.xsize, self.state.ysize = self.im.size\n else:\n self.state.xoff = x0\n self.state.yoff = y0\n self.state.xsize = x1 - x0\n self.state.ysize = y1 - y0\n\n if self.state.xsize <= 0 or self.state.ysize <= 0:\n msg = "Size cannot be negative"\n raise ValueError(msg)\n\n if (\n self.state.xsize + self.state.xoff > self.im.size[0]\n or self.state.ysize + self.state.yoff > self.im.size[1]\n ):\n msg = "Tile cannot extend outside image"\n raise ValueError(msg)\n\n\nclass PyDecoder(PyCodec):\n """\n Python implementation of a format decoder. Override this class and\n add the decoding logic in the :meth:`decode` method.\n\n See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`\n """\n\n _pulls_fd = False\n\n @property\n def pulls_fd(self) -> bool:\n return self._pulls_fd\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n """\n Override to perform the decoding process.\n\n :param buffer: A bytes object with the data to be decoded.\n :returns: A tuple of ``(bytes consumed, errcode)``.\n If finished with decoding return -1 for the bytes consumed.\n Err codes are from :data:`.ImageFile.ERRORS`.\n """\n msg = "unavailable in base decoder"\n raise NotImplementedError(msg)\n\n def set_as_raw(\n self, data: bytes, rawmode: str | None = None, extra: tuple[Any, ...] = ()\n ) -> None:\n """\n Convenience method to set the internal image from a stream of raw data\n\n :param data: Bytes to be set\n :param rawmode: The rawmode to be used for the decoder.\n If not specified, it will default to the mode of the image\n :param extra: Extra arguments for the decoder.\n :returns: None\n """\n\n if not rawmode:\n rawmode = self.mode\n d = Image._getdecoder(self.mode, "raw", rawmode, extra)\n assert self.im is not None\n d.setimage(self.im, self.state.extents())\n s = d.decode(data)\n\n if s[0] >= 0:\n msg = "not enough image data"\n raise ValueError(msg)\n if s[1] != 0:\n msg = "cannot decode image data"\n raise ValueError(msg)\n\n\nclass PyEncoder(PyCodec):\n """\n Python implementation of a format encoder. Override this class and\n add the decoding logic in the :meth:`encode` method.\n\n See :ref:`Writing Your Own File Codec in Python<file-codecs-py>`\n """\n\n _pushes_fd = False\n\n @property\n def pushes_fd(self) -> bool:\n return self._pushes_fd\n\n def encode(self, bufsize: int) -> tuple[int, int, bytes]:\n """\n Override to perform the encoding process.\n\n :param bufsize: Buffer size.\n :returns: A tuple of ``(bytes encoded, errcode, bytes)``.\n If finished with encoding return 1 for the error code.\n Err codes are from :data:`.ImageFile.ERRORS`.\n """\n msg = "unavailable in base encoder"\n raise NotImplementedError(msg)\n\n def encode_to_pyfd(self) -> tuple[int, int]:\n """\n If ``pushes_fd`` is ``True``, then this method will be used,\n and ``encode()`` will only be called once.\n\n :returns: A tuple of ``(bytes consumed, errcode)``.\n Err codes are from :data:`.ImageFile.ERRORS`.\n """\n if not self.pushes_fd:\n return 0, -8 # bad configuration\n bytes_consumed, errcode, data = self.encode(0)\n if data:\n assert self.fd is not None\n self.fd.write(data)\n return bytes_consumed, errcode\n\n def encode_to_file(self, fh: int, bufsize: int) -> int:\n """\n :param fh: File handle.\n :param bufsize: Buffer size.\n\n :returns: If finished successfully, return 0.\n Otherwise, return an error code. Err codes are from\n :data:`.ImageFile.ERRORS`.\n """\n errcode = 0\n while errcode == 0:\n status, errcode, buf = self.encode(bufsize)\n if status > 0:\n os.write(fh, buf[status:])\n return errcode\n | .venv\Lib\site-packages\PIL\ImageFile.py | ImageFile.py | Python | 30,256 | 0.95 | 0.215835 | 0.117493 | awesome-app | 967 | 2023-09-19T11:17:42.998321 | GPL-3.0 | false | 11dc9625534fa31a33b48aa06974de9b |
#\n# The Python Imaging Library.\n# $Id$\n#\n# standard filters\n#\n# History:\n# 1995-11-27 fl Created\n# 2002-06-08 fl Added rank and mode filters\n# 2003-09-15 fl Fixed rank calculation in rank filter; added expand call\n#\n# Copyright (c) 1997-2003 by Secret Labs AB.\n# Copyright (c) 1995-2002 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport abc\nimport functools\nfrom collections.abc import Sequence\nfrom types import ModuleType\nfrom typing import Any, Callable, cast\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from . import _imaging\n from ._typing import NumpyArray\n\n\nclass Filter(abc.ABC):\n @abc.abstractmethod\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n pass\n\n\nclass MultibandFilter(Filter):\n pass\n\n\nclass BuiltinFilter(MultibandFilter):\n filterargs: tuple[Any, ...]\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n if image.mode == "P":\n msg = "cannot filter palette images"\n raise ValueError(msg)\n return image.filter(*self.filterargs)\n\n\nclass Kernel(BuiltinFilter):\n """\n Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating\n point kernels.\n\n Kernels can only be applied to "L" and "RGB" images.\n\n :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5).\n :param kernel: A sequence containing kernel weights. The kernel will be flipped\n vertically before being applied to the image.\n :param scale: Scale factor. If given, the result for each pixel is divided by this\n value. The default is the sum of the kernel weights.\n :param offset: Offset. If given, this value is added to the result, after it has\n been divided by the scale factor.\n """\n\n name = "Kernel"\n\n def __init__(\n self,\n size: tuple[int, int],\n kernel: Sequence[float],\n scale: float | None = None,\n offset: float = 0,\n ) -> None:\n if scale is None:\n # default scale is sum of kernel\n scale = functools.reduce(lambda a, b: a + b, kernel)\n if size[0] * size[1] != len(kernel):\n msg = "not enough coefficients in kernel"\n raise ValueError(msg)\n self.filterargs = size, scale, offset, kernel\n\n\nclass RankFilter(Filter):\n """\n Create a rank filter. The rank filter sorts all pixels in\n a window of the given size, and returns the ``rank``'th value.\n\n :param size: The kernel size, in pixels.\n :param rank: What pixel value to pick. Use 0 for a min filter,\n ``size * size / 2`` for a median filter, ``size * size - 1``\n for a max filter, etc.\n """\n\n name = "Rank"\n\n def __init__(self, size: int, rank: int) -> None:\n self.size = size\n self.rank = rank\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n if image.mode == "P":\n msg = "cannot filter palette images"\n raise ValueError(msg)\n image = image.expand(self.size // 2, self.size // 2)\n return image.rankfilter(self.size, self.rank)\n\n\nclass MedianFilter(RankFilter):\n """\n Create a median filter. Picks the median pixel value in a window with the\n given size.\n\n :param size: The kernel size, in pixels.\n """\n\n name = "Median"\n\n def __init__(self, size: int = 3) -> None:\n self.size = size\n self.rank = size * size // 2\n\n\nclass MinFilter(RankFilter):\n """\n Create a min filter. Picks the lowest pixel value in a window with the\n given size.\n\n :param size: The kernel size, in pixels.\n """\n\n name = "Min"\n\n def __init__(self, size: int = 3) -> None:\n self.size = size\n self.rank = 0\n\n\nclass MaxFilter(RankFilter):\n """\n Create a max filter. Picks the largest pixel value in a window with the\n given size.\n\n :param size: The kernel size, in pixels.\n """\n\n name = "Max"\n\n def __init__(self, size: int = 3) -> None:\n self.size = size\n self.rank = size * size - 1\n\n\nclass ModeFilter(Filter):\n """\n Create a mode filter. Picks the most frequent pixel value in a box with the\n given size. Pixel values that occur only once or twice are ignored; if no\n pixel value occurs more than twice, the original pixel value is preserved.\n\n :param size: The kernel size, in pixels.\n """\n\n name = "Mode"\n\n def __init__(self, size: int = 3) -> None:\n self.size = size\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n return image.modefilter(self.size)\n\n\nclass GaussianBlur(MultibandFilter):\n """Blurs the image with a sequence of extended box filters, which\n approximates a Gaussian kernel. For details on accuracy see\n <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf>\n\n :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two\n numbers for x and y, or a single number for both.\n """\n\n name = "GaussianBlur"\n\n def __init__(self, radius: float | Sequence[float] = 2) -> None:\n self.radius = radius\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n xy = self.radius\n if isinstance(xy, (int, float)):\n xy = (xy, xy)\n if xy == (0, 0):\n return image.copy()\n return image.gaussian_blur(xy)\n\n\nclass BoxBlur(MultibandFilter):\n """Blurs the image by setting each pixel to the average value of the pixels\n in a square box extending radius pixels in each direction.\n Supports float radius of arbitrary size. Uses an optimized implementation\n which runs in linear time relative to the size of the image\n for any radius value.\n\n :param radius: Size of the box in a direction. Either a sequence of two numbers for\n x and y, or a single number for both.\n\n Radius 0 does not blur, returns an identical image.\n Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.\n """\n\n name = "BoxBlur"\n\n def __init__(self, radius: float | Sequence[float]) -> None:\n xy = radius if isinstance(radius, (tuple, list)) else (radius, radius)\n if xy[0] < 0 or xy[1] < 0:\n msg = "radius must be >= 0"\n raise ValueError(msg)\n self.radius = radius\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n xy = self.radius\n if isinstance(xy, (int, float)):\n xy = (xy, xy)\n if xy == (0, 0):\n return image.copy()\n return image.box_blur(xy)\n\n\nclass UnsharpMask(MultibandFilter):\n """Unsharp mask filter.\n\n See Wikipedia's entry on `digital unsharp masking`_ for an explanation of\n the parameters.\n\n :param radius: Blur Radius\n :param percent: Unsharp strength, in percent\n :param threshold: Threshold controls the minimum brightness change that\n will be sharpened\n\n .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking\n\n """\n\n name = "UnsharpMask"\n\n def __init__(\n self, radius: float = 2, percent: int = 150, threshold: int = 3\n ) -> None:\n self.radius = radius\n self.percent = percent\n self.threshold = threshold\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n return image.unsharp_mask(self.radius, self.percent, self.threshold)\n\n\nclass BLUR(BuiltinFilter):\n name = "Blur"\n # fmt: off\n filterargs = (5, 5), 16, 0, (\n 1, 1, 1, 1, 1,\n 1, 0, 0, 0, 1,\n 1, 0, 0, 0, 1,\n 1, 0, 0, 0, 1,\n 1, 1, 1, 1, 1,\n )\n # fmt: on\n\n\nclass CONTOUR(BuiltinFilter):\n name = "Contour"\n # fmt: off\n filterargs = (3, 3), 1, 255, (\n -1, -1, -1,\n -1, 8, -1,\n -1, -1, -1,\n )\n # fmt: on\n\n\nclass DETAIL(BuiltinFilter):\n name = "Detail"\n # fmt: off\n filterargs = (3, 3), 6, 0, (\n 0, -1, 0,\n -1, 10, -1,\n 0, -1, 0,\n )\n # fmt: on\n\n\nclass EDGE_ENHANCE(BuiltinFilter):\n name = "Edge-enhance"\n # fmt: off\n filterargs = (3, 3), 2, 0, (\n -1, -1, -1,\n -1, 10, -1,\n -1, -1, -1,\n )\n # fmt: on\n\n\nclass EDGE_ENHANCE_MORE(BuiltinFilter):\n name = "Edge-enhance More"\n # fmt: off\n filterargs = (3, 3), 1, 0, (\n -1, -1, -1,\n -1, 9, -1,\n -1, -1, -1,\n )\n # fmt: on\n\n\nclass EMBOSS(BuiltinFilter):\n name = "Emboss"\n # fmt: off\n filterargs = (3, 3), 1, 128, (\n -1, 0, 0,\n 0, 1, 0,\n 0, 0, 0,\n )\n # fmt: on\n\n\nclass FIND_EDGES(BuiltinFilter):\n name = "Find Edges"\n # fmt: off\n filterargs = (3, 3), 1, 0, (\n -1, -1, -1,\n -1, 8, -1,\n -1, -1, -1,\n )\n # fmt: on\n\n\nclass SHARPEN(BuiltinFilter):\n name = "Sharpen"\n # fmt: off\n filterargs = (3, 3), 16, 0, (\n -2, -2, -2,\n -2, 32, -2,\n -2, -2, -2,\n )\n # fmt: on\n\n\nclass SMOOTH(BuiltinFilter):\n name = "Smooth"\n # fmt: off\n filterargs = (3, 3), 13, 0, (\n 1, 1, 1,\n 1, 5, 1,\n 1, 1, 1,\n )\n # fmt: on\n\n\nclass SMOOTH_MORE(BuiltinFilter):\n name = "Smooth More"\n # fmt: off\n filterargs = (5, 5), 100, 0, (\n 1, 1, 1, 1, 1,\n 1, 5, 5, 5, 1,\n 1, 5, 44, 5, 1,\n 1, 5, 5, 5, 1,\n 1, 1, 1, 1, 1,\n )\n # fmt: on\n\n\nclass Color3DLUT(MultibandFilter):\n """Three-dimensional color lookup table.\n\n Transforms 3-channel pixels using the values of the channels as coordinates\n in the 3D lookup table and interpolating the nearest elements.\n\n This method allows you to apply almost any color transformation\n in constant time by using pre-calculated decimated tables.\n\n .. versionadded:: 5.2.0\n\n :param size: Size of the table. One int or tuple of (int, int, int).\n Minimal size in any dimension is 2, maximum is 65.\n :param table: Flat lookup table. A list of ``channels * size**3``\n float elements or a list of ``size**3`` channels-sized\n tuples with floats. Channels are changed first,\n then first dimension, then second, then third.\n Value 0.0 corresponds lowest value of output, 1.0 highest.\n :param channels: Number of channels in the table. Could be 3 or 4.\n Default is 3.\n :param target_mode: A mode for the result image. Should have not less\n than ``channels`` channels. Default is ``None``,\n which means that mode wouldn't be changed.\n """\n\n name = "Color 3D LUT"\n\n def __init__(\n self,\n size: int | tuple[int, int, int],\n table: Sequence[float] | Sequence[Sequence[int]] | NumpyArray,\n channels: int = 3,\n target_mode: str | None = None,\n **kwargs: bool,\n ) -> None:\n if channels not in (3, 4):\n msg = "Only 3 or 4 output channels are supported"\n raise ValueError(msg)\n self.size = size = self._check_size(size)\n self.channels = channels\n self.mode = target_mode\n\n # Hidden flag `_copy_table=False` could be used to avoid extra copying\n # of the table if the table is specially made for the constructor.\n copy_table = kwargs.get("_copy_table", True)\n items = size[0] * size[1] * size[2]\n wrong_size = False\n\n numpy: ModuleType | None = None\n if hasattr(table, "shape"):\n try:\n import numpy\n except ImportError:\n pass\n\n if numpy and isinstance(table, numpy.ndarray):\n numpy_table: NumpyArray = table\n if copy_table:\n numpy_table = numpy_table.copy()\n\n if numpy_table.shape in [\n (items * channels,),\n (items, channels),\n (size[2], size[1], size[0], channels),\n ]:\n table = numpy_table.reshape(items * channels)\n else:\n wrong_size = True\n\n else:\n if copy_table:\n table = list(table)\n\n # Convert to a flat list\n if table and isinstance(table[0], (list, tuple)):\n raw_table = cast(Sequence[Sequence[int]], table)\n flat_table: list[int] = []\n for pixel in raw_table:\n if len(pixel) != channels:\n msg = (\n "The elements of the table should "\n f"have a length of {channels}."\n )\n raise ValueError(msg)\n flat_table.extend(pixel)\n table = flat_table\n\n if wrong_size or len(table) != items * channels:\n msg = (\n "The table should have either channels * size**3 float items "\n "or size**3 items of channels-sized tuples with floats. "\n f"Table should be: {channels}x{size[0]}x{size[1]}x{size[2]}. "\n f"Actual length: {len(table)}"\n )\n raise ValueError(msg)\n self.table = table\n\n @staticmethod\n def _check_size(size: Any) -> tuple[int, int, int]:\n try:\n _, _, _ = size\n except ValueError as e:\n msg = "Size should be either an integer or a tuple of three integers."\n raise ValueError(msg) from e\n except TypeError:\n size = (size, size, size)\n size = tuple(int(x) for x in size)\n for size_1d in size:\n if not 2 <= size_1d <= 65:\n msg = "Size should be in [2, 65] range."\n raise ValueError(msg)\n return size\n\n @classmethod\n def generate(\n cls,\n size: int | tuple[int, int, int],\n callback: Callable[[float, float, float], tuple[float, ...]],\n channels: int = 3,\n target_mode: str | None = None,\n ) -> Color3DLUT:\n """Generates new LUT using provided callback.\n\n :param size: Size of the table. Passed to the constructor.\n :param callback: Function with three parameters which correspond\n three color channels. Will be called ``size**3``\n times with values from 0.0 to 1.0 and should return\n a tuple with ``channels`` elements.\n :param channels: The number of channels which should return callback.\n :param target_mode: Passed to the constructor of the resulting\n lookup table.\n """\n size_1d, size_2d, size_3d = cls._check_size(size)\n if channels not in (3, 4):\n msg = "Only 3 or 4 output channels are supported"\n raise ValueError(msg)\n\n table: list[float] = [0] * (size_1d * size_2d * size_3d * channels)\n idx_out = 0\n for b in range(size_3d):\n for g in range(size_2d):\n for r in range(size_1d):\n table[idx_out : idx_out + channels] = callback(\n r / (size_1d - 1), g / (size_2d - 1), b / (size_3d - 1)\n )\n idx_out += channels\n\n return cls(\n (size_1d, size_2d, size_3d),\n table,\n channels=channels,\n target_mode=target_mode,\n _copy_table=False,\n )\n\n def transform(\n self,\n callback: Callable[..., tuple[float, ...]],\n with_normals: bool = False,\n channels: int | None = None,\n target_mode: str | None = None,\n ) -> Color3DLUT:\n """Transforms the table values using provided callback and returns\n a new LUT with altered values.\n\n :param callback: A function which takes old lookup table values\n and returns a new set of values. The number\n of arguments which function should take is\n ``self.channels`` or ``3 + self.channels``\n if ``with_normals`` flag is set.\n Should return a tuple of ``self.channels`` or\n ``channels`` elements if it is set.\n :param with_normals: If true, ``callback`` will be called with\n coordinates in the color cube as the first\n three arguments. Otherwise, ``callback``\n will be called only with actual color values.\n :param channels: The number of channels in the resulting lookup table.\n :param target_mode: Passed to the constructor of the resulting\n lookup table.\n """\n if channels not in (None, 3, 4):\n msg = "Only 3 or 4 output channels are supported"\n raise ValueError(msg)\n ch_in = self.channels\n ch_out = channels or ch_in\n size_1d, size_2d, size_3d = self.size\n\n table: list[float] = [0] * (size_1d * size_2d * size_3d * ch_out)\n idx_in = 0\n idx_out = 0\n for b in range(size_3d):\n for g in range(size_2d):\n for r in range(size_1d):\n values = self.table[idx_in : idx_in + ch_in]\n if with_normals:\n values = callback(\n r / (size_1d - 1),\n g / (size_2d - 1),\n b / (size_3d - 1),\n *values,\n )\n else:\n values = callback(*values)\n table[idx_out : idx_out + ch_out] = values\n idx_in += ch_in\n idx_out += ch_out\n\n return type(self)(\n self.size,\n table,\n channels=ch_out,\n target_mode=target_mode or self.mode,\n _copy_table=False,\n )\n\n def __repr__(self) -> str:\n r = [\n f"{self.__class__.__name__} from {self.table.__class__.__name__}",\n "size={:d}x{:d}x{:d}".format(*self.size),\n f"channels={self.channels:d}",\n ]\n if self.mode:\n r.append(f"target_mode={self.mode}")\n return "<{}>".format(" ".join(r))\n\n def filter(self, image: _imaging.ImagingCore) -> _imaging.ImagingCore:\n from . import Image\n\n return image.color_lut_3d(\n self.mode or image.mode,\n Image.Resampling.BILINEAR,\n self.channels,\n self.size,\n self.table,\n )\n | .venv\Lib\site-packages\PIL\ImageFilter.py | ImageFilter.py | Python | 19,275 | 0.95 | 0.165563 | 0.085193 | node-utils | 449 | 2023-08-27T23:39:54.563763 | BSD-3-Clause | false | 5f7efd3f00cd9fa550163686be6bdfff |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PIL raster font management\n#\n# History:\n# 1996-08-07 fl created (experimental)\n# 1997-08-25 fl minor adjustments to handle fonts from pilfont 0.3\n# 1999-02-06 fl rewrote most font management stuff in C\n# 1999-03-17 fl take pth files into account in load_path (from Richard Jones)\n# 2001-02-17 fl added freetype support\n# 2001-05-09 fl added TransposedFont wrapper class\n# 2002-03-04 fl make sure we have a "L" or "1" font\n# 2002-12-04 fl skip non-directory entries in the system path\n# 2003-04-29 fl add embedded default font\n# 2003-09-27 fl added support for truetype charmap encodings\n#\n# Todo:\n# Adapt to PILFONT2 format (16-bit fonts, compressed, single file)\n#\n# Copyright (c) 1997-2003 by Secret Labs AB\n# Copyright (c) 1996-2003 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\n\nfrom __future__ import annotations\n\nimport base64\nimport os\nimport sys\nimport warnings\nfrom enum import IntEnum\nfrom io import BytesIO\nfrom types import ModuleType\nfrom typing import IO, Any, BinaryIO, TypedDict, cast\n\nfrom . import Image, features\nfrom ._typing import StrOrBytesPath\nfrom ._util import DeferredError, is_path\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from . import ImageFile\n from ._imaging import ImagingFont\n from ._imagingft import Font\n\n\nclass Axis(TypedDict):\n minimum: int | None\n default: int | None\n maximum: int | None\n name: bytes | None\n\n\nclass Layout(IntEnum):\n BASIC = 0\n RAQM = 1\n\n\nMAX_STRING_LENGTH = 1_000_000\n\n\ncore: ModuleType | DeferredError\ntry:\n from . import _imagingft as core\nexcept ImportError as ex:\n core = DeferredError.new(ex)\n\n\ndef _string_length_check(text: str | bytes | bytearray) -> None:\n if MAX_STRING_LENGTH is not None and len(text) > MAX_STRING_LENGTH:\n msg = "too many characters in string"\n raise ValueError(msg)\n\n\n# FIXME: add support for pilfont2 format (see FontFile.py)\n\n# --------------------------------------------------------------------\n# Font metrics format:\n# "PILfont" LF\n# fontdescriptor LF\n# (optional) key=value... LF\n# "DATA" LF\n# binary data: 256*10*2 bytes (dx, dy, dstbox, srcbox)\n#\n# To place a character, cut out srcbox and paste at dstbox,\n# relative to the character position. Then move the character\n# position according to dx, dy.\n# --------------------------------------------------------------------\n\n\nclass ImageFont:\n """PIL font wrapper"""\n\n font: ImagingFont\n\n def _load_pilfont(self, filename: str) -> None:\n with open(filename, "rb") as fp:\n image: ImageFile.ImageFile | None = None\n root = os.path.splitext(filename)[0]\n\n for ext in (".png", ".gif", ".pbm"):\n if image:\n image.close()\n try:\n fullname = root + ext\n image = Image.open(fullname)\n except Exception:\n pass\n else:\n if image and image.mode in ("1", "L"):\n break\n else:\n if image:\n image.close()\n\n msg = f"cannot find glyph data file {root}.{{gif|pbm|png}}"\n raise OSError(msg)\n\n self.file = fullname\n\n self._load_pilfont_data(fp, image)\n image.close()\n\n def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:\n # read PILfont header\n if file.readline() != b"PILfont\n":\n msg = "Not a PILfont file"\n raise SyntaxError(msg)\n file.readline().split(b";")\n self.info = [] # FIXME: should be a dictionary\n while True:\n s = file.readline()\n if not s or s == b"DATA\n":\n break\n self.info.append(s)\n\n # read PILfont metrics\n data = file.read(256 * 20)\n\n # check image\n if image.mode not in ("1", "L"):\n msg = "invalid font image mode"\n raise TypeError(msg)\n\n image.load()\n\n self.font = Image.core.font(image.im, data)\n\n def getmask(\n self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any\n ) -> Image.core.ImagingCore:\n """\n Create a bitmap for the text.\n\n If the font uses antialiasing, the bitmap should have mode ``L`` and use a\n maximum value of 255. Otherwise, it should have mode ``1``.\n\n :param text: Text to render.\n :param mode: Used by some graphics drivers to indicate what mode the\n driver prefers; if empty, the renderer may return either\n mode. Note that the mode is always a string, to simplify\n C-level implementations.\n\n .. versionadded:: 1.1.5\n\n :return: An internal PIL storage memory instance as defined by the\n :py:mod:`PIL.Image.core` interface module.\n """\n _string_length_check(text)\n Image._decompression_bomb_check(self.font.getsize(text))\n return self.font.getmask(text, mode)\n\n def getbbox(\n self, text: str | bytes | bytearray, *args: Any, **kwargs: Any\n ) -> tuple[int, int, int, int]:\n """\n Returns bounding box (in pixels) of given text.\n\n .. versionadded:: 9.2.0\n\n :param text: Text to render.\n\n :return: ``(left, top, right, bottom)`` bounding box\n """\n _string_length_check(text)\n width, height = self.font.getsize(text)\n return 0, 0, width, height\n\n def getlength(\n self, text: str | bytes | bytearray, *args: Any, **kwargs: Any\n ) -> int:\n """\n Returns length (in pixels) of given text.\n This is the amount by which following text should be offset.\n\n .. versionadded:: 9.2.0\n """\n _string_length_check(text)\n width, height = self.font.getsize(text)\n return width\n\n\n##\n# Wrapper for FreeType fonts. Application code should use the\n# <b>truetype</b> factory function to create font objects.\n\n\nclass FreeTypeFont:\n """FreeType font wrapper (requires _imagingft service)"""\n\n font: Font\n font_bytes: bytes\n\n def __init__(\n self,\n font: StrOrBytesPath | BinaryIO,\n size: float = 10,\n index: int = 0,\n encoding: str = "",\n layout_engine: Layout | None = None,\n ) -> None:\n # FIXME: use service provider instead\n\n if isinstance(core, DeferredError):\n raise core.ex\n\n if size <= 0:\n msg = f"font size must be greater than 0, not {size}"\n raise ValueError(msg)\n\n self.path = font\n self.size = size\n self.index = index\n self.encoding = encoding\n\n try:\n from packaging.version import parse as parse_version\n except ImportError:\n pass\n else:\n if freetype_version := features.version_module("freetype2"):\n if parse_version(freetype_version) < parse_version("2.9.1"):\n warnings.warn(\n "Support for FreeType 2.9.0 is deprecated and will be removed "\n "in Pillow 12 (2025-10-15). Please upgrade to FreeType 2.9.1 "\n "or newer, preferably FreeType 2.10.4 which fixes "\n "CVE-2020-15999.",\n DeprecationWarning,\n )\n\n if layout_engine not in (Layout.BASIC, Layout.RAQM):\n layout_engine = Layout.BASIC\n if core.HAVE_RAQM:\n layout_engine = Layout.RAQM\n elif layout_engine == Layout.RAQM and not core.HAVE_RAQM:\n warnings.warn(\n "Raqm layout was requested, but Raqm is not available. "\n "Falling back to basic layout."\n )\n layout_engine = Layout.BASIC\n\n self.layout_engine = layout_engine\n\n def load_from_bytes(f: IO[bytes]) -> None:\n self.font_bytes = f.read()\n self.font = core.getfont(\n "", size, index, encoding, self.font_bytes, layout_engine\n )\n\n if is_path(font):\n font = os.fspath(font)\n if sys.platform == "win32":\n font_bytes_path = font if isinstance(font, bytes) else font.encode()\n try:\n font_bytes_path.decode("ascii")\n except UnicodeDecodeError:\n # FreeType cannot load fonts with non-ASCII characters on Windows\n # So load it into memory first\n with open(font, "rb") as f:\n load_from_bytes(f)\n return\n self.font = core.getfont(\n font, size, index, encoding, layout_engine=layout_engine\n )\n else:\n load_from_bytes(cast(IO[bytes], font))\n\n def __getstate__(self) -> list[Any]:\n return [self.path, self.size, self.index, self.encoding, self.layout_engine]\n\n def __setstate__(self, state: list[Any]) -> None:\n path, size, index, encoding, layout_engine = state\n FreeTypeFont.__init__(self, path, size, index, encoding, layout_engine)\n\n def getname(self) -> tuple[str | None, str | None]:\n """\n :return: A tuple of the font family (e.g. Helvetica) and the font style\n (e.g. Bold)\n """\n return self.font.family, self.font.style\n\n def getmetrics(self) -> tuple[int, int]:\n """\n :return: A tuple of the font ascent (the distance from the baseline to\n the highest outline point) and descent (the distance from the\n baseline to the lowest outline point, a negative value)\n """\n return self.font.ascent, self.font.descent\n\n def getlength(\n self,\n text: str | bytes,\n mode: str = "",\n direction: str | None = None,\n features: list[str] | None = None,\n language: str | None = None,\n ) -> float:\n """\n Returns length (in pixels with 1/64 precision) of given text when rendered\n in font with provided direction, features, and language.\n\n This is the amount by which following text should be offset.\n Text bounding box may extend past the length in some fonts,\n e.g. when using italics or accents.\n\n The result is returned as a float; it is a whole number if using basic layout.\n\n Note that the sum of two lengths may not equal the length of a concatenated\n string due to kerning. If you need to adjust for kerning, include the following\n character and subtract its length.\n\n For example, instead of ::\n\n hello = font.getlength("Hello")\n world = font.getlength("World")\n hello_world = hello + world # not adjusted for kerning\n assert hello_world == font.getlength("HelloWorld") # may fail\n\n use ::\n\n hello = font.getlength("HelloW") - font.getlength("W") # adjusted for kerning\n world = font.getlength("World")\n hello_world = hello + world # adjusted for kerning\n assert hello_world == font.getlength("HelloWorld") # True\n\n or disable kerning with (requires libraqm) ::\n\n hello = draw.textlength("Hello", font, features=["-kern"])\n world = draw.textlength("World", font, features=["-kern"])\n hello_world = hello + world # kerning is disabled, no need to adjust\n assert hello_world == draw.textlength("HelloWorld", font, features=["-kern"])\n\n .. versionadded:: 8.0.0\n\n :param text: Text to measure.\n :param mode: Used by some graphics drivers to indicate what mode the\n driver prefers; if empty, the renderer may return either\n mode. Note that the mode is always a string, to simplify\n C-level implementations.\n\n :param direction: Direction of the text. It can be 'rtl' (right to\n left), 'ltr' (left to right) or 'ttb' (top to bottom).\n Requires libraqm.\n\n :param features: A list of OpenType font features to be used during text\n layout. This is usually used to turn on optional\n font features that are not enabled by default,\n for example 'dlig' or 'ss01', but can be also\n used to turn off default font features for\n example '-liga' to disable ligatures or '-kern'\n to disable kerning. To get all supported\n features, see\n https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist\n Requires libraqm.\n\n :param language: Language of the text. Different languages may use\n different glyph shapes or ligatures. This parameter tells\n the font which language the text is in, and to apply the\n correct substitutions as appropriate, if available.\n It should be a `BCP 47 language code\n <https://www.w3.org/International/articles/language-tags/>`_\n Requires libraqm.\n\n :return: Either width for horizontal text, or height for vertical text.\n """\n _string_length_check(text)\n return self.font.getlength(text, mode, direction, features, language) / 64\n\n def getbbox(\n self,\n text: str | bytes,\n mode: str = "",\n direction: str | None = None,\n features: list[str] | None = None,\n language: str | None = None,\n stroke_width: float = 0,\n anchor: str | None = None,\n ) -> tuple[float, float, float, float]:\n """\n Returns bounding box (in pixels) of given text relative to given anchor\n when rendered in font with provided direction, features, and language.\n\n Use :py:meth:`getlength()` to get the offset of following text with\n 1/64 pixel precision. The bounding box includes extra margins for\n some fonts, e.g. italics or accents.\n\n .. versionadded:: 8.0.0\n\n :param text: Text to render.\n :param mode: Used by some graphics drivers to indicate what mode the\n driver prefers; if empty, the renderer may return either\n mode. Note that the mode is always a string, to simplify\n C-level implementations.\n\n :param direction: Direction of the text. It can be 'rtl' (right to\n left), 'ltr' (left to right) or 'ttb' (top to bottom).\n Requires libraqm.\n\n :param features: A list of OpenType font features to be used during text\n layout. This is usually used to turn on optional\n font features that are not enabled by default,\n for example 'dlig' or 'ss01', but can be also\n used to turn off default font features for\n example '-liga' to disable ligatures or '-kern'\n to disable kerning. To get all supported\n features, see\n https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist\n Requires libraqm.\n\n :param language: Language of the text. Different languages may use\n different glyph shapes or ligatures. This parameter tells\n the font which language the text is in, and to apply the\n correct substitutions as appropriate, if available.\n It should be a `BCP 47 language code\n <https://www.w3.org/International/articles/language-tags/>`_\n Requires libraqm.\n\n :param stroke_width: The width of the text stroke.\n\n :param anchor: The text anchor alignment. Determines the relative location of\n the anchor to the text. The default alignment is top left,\n specifically ``la`` for horizontal text and ``lt`` for\n vertical text. See :ref:`text-anchors` for details.\n\n :return: ``(left, top, right, bottom)`` bounding box\n """\n _string_length_check(text)\n size, offset = self.font.getsize(\n text, mode, direction, features, language, anchor\n )\n left, top = offset[0] - stroke_width, offset[1] - stroke_width\n width, height = size[0] + 2 * stroke_width, size[1] + 2 * stroke_width\n return left, top, left + width, top + height\n\n def getmask(\n self,\n text: str | bytes,\n mode: str = "",\n direction: str | None = None,\n features: list[str] | None = None,\n language: str | None = None,\n stroke_width: float = 0,\n anchor: str | None = None,\n ink: int = 0,\n start: tuple[float, float] | None = None,\n ) -> Image.core.ImagingCore:\n """\n Create a bitmap for the text.\n\n If the font uses antialiasing, the bitmap should have mode ``L`` and use a\n maximum value of 255. If the font has embedded color data, the bitmap\n should have mode ``RGBA``. Otherwise, it should have mode ``1``.\n\n :param text: Text to render.\n :param mode: Used by some graphics drivers to indicate what mode the\n driver prefers; if empty, the renderer may return either\n mode. Note that the mode is always a string, to simplify\n C-level implementations.\n\n .. versionadded:: 1.1.5\n\n :param direction: Direction of the text. It can be 'rtl' (right to\n left), 'ltr' (left to right) or 'ttb' (top to bottom).\n Requires libraqm.\n\n .. versionadded:: 4.2.0\n\n :param features: A list of OpenType font features to be used during text\n layout. This is usually used to turn on optional\n font features that are not enabled by default,\n for example 'dlig' or 'ss01', but can be also\n used to turn off default font features for\n example '-liga' to disable ligatures or '-kern'\n to disable kerning. To get all supported\n features, see\n https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist\n Requires libraqm.\n\n .. versionadded:: 4.2.0\n\n :param language: Language of the text. Different languages may use\n different glyph shapes or ligatures. This parameter tells\n the font which language the text is in, and to apply the\n correct substitutions as appropriate, if available.\n It should be a `BCP 47 language code\n <https://www.w3.org/International/articles/language-tags/>`_\n Requires libraqm.\n\n .. versionadded:: 6.0.0\n\n :param stroke_width: The width of the text stroke.\n\n .. versionadded:: 6.2.0\n\n :param anchor: The text anchor alignment. Determines the relative location of\n the anchor to the text. The default alignment is top left,\n specifically ``la`` for horizontal text and ``lt`` for\n vertical text. See :ref:`text-anchors` for details.\n\n .. versionadded:: 8.0.0\n\n :param ink: Foreground ink for rendering in RGBA mode.\n\n .. versionadded:: 8.0.0\n\n :param start: Tuple of horizontal and vertical offset, as text may render\n differently when starting at fractional coordinates.\n\n .. versionadded:: 9.4.0\n\n :return: An internal PIL storage memory instance as defined by the\n :py:mod:`PIL.Image.core` interface module.\n """\n return self.getmask2(\n text,\n mode,\n direction=direction,\n features=features,\n language=language,\n stroke_width=stroke_width,\n anchor=anchor,\n ink=ink,\n start=start,\n )[0]\n\n def getmask2(\n self,\n text: str | bytes,\n mode: str = "",\n direction: str | None = None,\n features: list[str] | None = None,\n language: str | None = None,\n stroke_width: float = 0,\n anchor: str | None = None,\n ink: int = 0,\n start: tuple[float, float] | None = None,\n *args: Any,\n **kwargs: Any,\n ) -> tuple[Image.core.ImagingCore, tuple[int, int]]:\n """\n Create a bitmap for the text.\n\n If the font uses antialiasing, the bitmap should have mode ``L`` and use a\n maximum value of 255. If the font has embedded color data, the bitmap\n should have mode ``RGBA``. Otherwise, it should have mode ``1``.\n\n :param text: Text to render.\n :param mode: Used by some graphics drivers to indicate what mode the\n driver prefers; if empty, the renderer may return either\n mode. Note that the mode is always a string, to simplify\n C-level implementations.\n\n .. versionadded:: 1.1.5\n\n :param direction: Direction of the text. It can be 'rtl' (right to\n left), 'ltr' (left to right) or 'ttb' (top to bottom).\n Requires libraqm.\n\n .. versionadded:: 4.2.0\n\n :param features: A list of OpenType font features to be used during text\n layout. This is usually used to turn on optional\n font features that are not enabled by default,\n for example 'dlig' or 'ss01', but can be also\n used to turn off default font features for\n example '-liga' to disable ligatures or '-kern'\n to disable kerning. To get all supported\n features, see\n https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist\n Requires libraqm.\n\n .. versionadded:: 4.2.0\n\n :param language: Language of the text. Different languages may use\n different glyph shapes or ligatures. This parameter tells\n the font which language the text is in, and to apply the\n correct substitutions as appropriate, if available.\n It should be a `BCP 47 language code\n <https://www.w3.org/International/articles/language-tags/>`_\n Requires libraqm.\n\n .. versionadded:: 6.0.0\n\n :param stroke_width: The width of the text stroke.\n\n .. versionadded:: 6.2.0\n\n :param anchor: The text anchor alignment. Determines the relative location of\n the anchor to the text. The default alignment is top left,\n specifically ``la`` for horizontal text and ``lt`` for\n vertical text. See :ref:`text-anchors` for details.\n\n .. versionadded:: 8.0.0\n\n :param ink: Foreground ink for rendering in RGBA mode.\n\n .. versionadded:: 8.0.0\n\n :param start: Tuple of horizontal and vertical offset, as text may render\n differently when starting at fractional coordinates.\n\n .. versionadded:: 9.4.0\n\n :return: A tuple of an internal PIL storage memory instance as defined by the\n :py:mod:`PIL.Image.core` interface module, and the text offset, the\n gap between the starting coordinate and the first marking\n """\n _string_length_check(text)\n if start is None:\n start = (0, 0)\n\n def fill(width: int, height: int) -> Image.core.ImagingCore:\n size = (width, height)\n Image._decompression_bomb_check(size)\n return Image.core.fill("RGBA" if mode == "RGBA" else "L", size)\n\n return self.font.render(\n text,\n fill,\n mode,\n direction,\n features,\n language,\n stroke_width,\n kwargs.get("stroke_filled", False),\n anchor,\n ink,\n start,\n )\n\n def font_variant(\n self,\n font: StrOrBytesPath | BinaryIO | None = None,\n size: float | None = None,\n index: int | None = None,\n encoding: str | None = None,\n layout_engine: Layout | None = None,\n ) -> FreeTypeFont:\n """\n Create a copy of this FreeTypeFont object,\n using any specified arguments to override the settings.\n\n Parameters are identical to the parameters used to initialize this\n object.\n\n :return: A FreeTypeFont object.\n """\n if font is None:\n try:\n font = BytesIO(self.font_bytes)\n except AttributeError:\n font = self.path\n return FreeTypeFont(\n font=font,\n size=self.size if size is None else size,\n index=self.index if index is None else index,\n encoding=self.encoding if encoding is None else encoding,\n layout_engine=layout_engine or self.layout_engine,\n )\n\n def get_variation_names(self) -> list[bytes]:\n """\n :returns: A list of the named styles in a variation font.\n :exception OSError: If the font is not a variation font.\n """\n try:\n names = self.font.getvarnames()\n except AttributeError as e:\n msg = "FreeType 2.9.1 or greater is required"\n raise NotImplementedError(msg) from e\n return [name.replace(b"\x00", b"") for name in names]\n\n def set_variation_by_name(self, name: str | bytes) -> None:\n """\n :param name: The name of the style.\n :exception OSError: If the font is not a variation font.\n """\n names = self.get_variation_names()\n if not isinstance(name, bytes):\n name = name.encode()\n index = names.index(name) + 1\n\n if index == getattr(self, "_last_variation_index", None):\n # When the same name is set twice in a row,\n # there is an 'unknown freetype error'\n # https://savannah.nongnu.org/bugs/?56186\n return\n self._last_variation_index = index\n\n self.font.setvarname(index)\n\n def get_variation_axes(self) -> list[Axis]:\n """\n :returns: A list of the axes in a variation font.\n :exception OSError: If the font is not a variation font.\n """\n try:\n axes = self.font.getvaraxes()\n except AttributeError as e:\n msg = "FreeType 2.9.1 or greater is required"\n raise NotImplementedError(msg) from e\n for axis in axes:\n if axis["name"]:\n axis["name"] = axis["name"].replace(b"\x00", b"")\n return axes\n\n def set_variation_by_axes(self, axes: list[float]) -> None:\n """\n :param axes: A list of values for each axis.\n :exception OSError: If the font is not a variation font.\n """\n try:\n self.font.setvaraxes(axes)\n except AttributeError as e:\n msg = "FreeType 2.9.1 or greater is required"\n raise NotImplementedError(msg) from e\n\n\nclass TransposedFont:\n """Wrapper for writing rotated or mirrored text"""\n\n def __init__(\n self, font: ImageFont | FreeTypeFont, orientation: Image.Transpose | None = None\n ):\n """\n Wrapper that creates a transposed font from any existing font\n object.\n\n :param font: A font object.\n :param orientation: An optional orientation. If given, this should\n be one of Image.Transpose.FLIP_LEFT_RIGHT, Image.Transpose.FLIP_TOP_BOTTOM,\n Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, or\n Image.Transpose.ROTATE_270.\n """\n self.font = font\n self.orientation = orientation # any 'transpose' argument, or None\n\n def getmask(\n self, text: str | bytes, mode: str = "", *args: Any, **kwargs: Any\n ) -> Image.core.ImagingCore:\n im = self.font.getmask(text, mode, *args, **kwargs)\n if self.orientation is not None:\n return im.transpose(self.orientation)\n return im\n\n def getbbox(\n self, text: str | bytes, *args: Any, **kwargs: Any\n ) -> tuple[int, int, float, float]:\n # TransposedFont doesn't support getmask2, move top-left point to (0, 0)\n # this has no effect on ImageFont and simulates anchor="lt" for FreeTypeFont\n left, top, right, bottom = self.font.getbbox(text, *args, **kwargs)\n width = right - left\n height = bottom - top\n if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):\n return 0, 0, height, width\n return 0, 0, width, height\n\n def getlength(self, text: str | bytes, *args: Any, **kwargs: Any) -> float:\n if self.orientation in (Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_270):\n msg = "text length is undefined for text rotated by 90 or 270 degrees"\n raise ValueError(msg)\n return self.font.getlength(text, *args, **kwargs)\n\n\ndef load(filename: str) -> ImageFont:\n """\n Load a font file. This function loads a font object from the given\n bitmap font file, and returns the corresponding font object. For loading TrueType\n or OpenType fonts instead, see :py:func:`~PIL.ImageFont.truetype`.\n\n :param filename: Name of font file.\n :return: A font object.\n :exception OSError: If the file could not be read.\n """\n f = ImageFont()\n f._load_pilfont(filename)\n return f\n\n\ndef truetype(\n font: StrOrBytesPath | BinaryIO,\n size: float = 10,\n index: int = 0,\n encoding: str = "",\n layout_engine: Layout | None = None,\n) -> FreeTypeFont:\n """\n Load a TrueType or OpenType font from a file or file-like object,\n and create a font object. This function loads a font object from the given\n file or file-like object, and creates a font object for a font of the given\n size. For loading bitmap fonts instead, see :py:func:`~PIL.ImageFont.load`\n and :py:func:`~PIL.ImageFont.load_path`.\n\n Pillow uses FreeType to open font files. On Windows, be aware that FreeType\n will keep the file open as long as the FreeTypeFont object exists. Windows\n limits the number of files that can be open in C at once to 512, so if many\n fonts are opened simultaneously and that limit is approached, an\n ``OSError`` may be thrown, reporting that FreeType "cannot open resource".\n A workaround would be to copy the file(s) into memory, and open that instead.\n\n This function requires the _imagingft service.\n\n :param font: A filename or file-like object containing a TrueType font.\n If the file is not found in this filename, the loader may also\n search in other directories, such as:\n\n * The :file:`fonts/` directory on Windows,\n * :file:`/Library/Fonts/`, :file:`/System/Library/Fonts/`\n and :file:`~/Library/Fonts/` on macOS.\n * :file:`~/.local/share/fonts`, :file:`/usr/local/share/fonts`,\n and :file:`/usr/share/fonts` on Linux; or those specified by\n the ``XDG_DATA_HOME`` and ``XDG_DATA_DIRS`` environment variables\n for user-installed and system-wide fonts, respectively.\n\n :param size: The requested size, in pixels.\n :param index: Which font face to load (default is first available face).\n :param encoding: Which font encoding to use (default is Unicode). Possible\n encodings include (see the FreeType documentation for more\n information):\n\n * "unic" (Unicode)\n * "symb" (Microsoft Symbol)\n * "ADOB" (Adobe Standard)\n * "ADBE" (Adobe Expert)\n * "ADBC" (Adobe Custom)\n * "armn" (Apple Roman)\n * "sjis" (Shift JIS)\n * "gb " (PRC)\n * "big5"\n * "wans" (Extended Wansung)\n * "joha" (Johab)\n * "lat1" (Latin-1)\n\n This specifies the character set to use. It does not alter the\n encoding of any text provided in subsequent operations.\n :param layout_engine: Which layout engine to use, if available:\n :attr:`.ImageFont.Layout.BASIC` or :attr:`.ImageFont.Layout.RAQM`.\n If it is available, Raqm layout will be used by default.\n Otherwise, basic layout will be used.\n\n Raqm layout is recommended for all non-English text. If Raqm layout\n is not required, basic layout will have better performance.\n\n You can check support for Raqm layout using\n :py:func:`PIL.features.check_feature` with ``feature="raqm"``.\n\n .. versionadded:: 4.2.0\n :return: A font object.\n :exception OSError: If the file could not be read.\n :exception ValueError: If the font size is not greater than zero.\n """\n\n def freetype(font: StrOrBytesPath | BinaryIO) -> FreeTypeFont:\n return FreeTypeFont(font, size, index, encoding, layout_engine)\n\n try:\n return freetype(font)\n except OSError:\n if not is_path(font):\n raise\n ttf_filename = os.path.basename(font)\n\n dirs = []\n if sys.platform == "win32":\n # check the windows font repository\n # NOTE: must use uppercase WINDIR, to work around bugs in\n # 1.5.2's os.environ.get()\n windir = os.environ.get("WINDIR")\n if windir:\n dirs.append(os.path.join(windir, "fonts"))\n elif sys.platform in ("linux", "linux2"):\n data_home = os.environ.get("XDG_DATA_HOME")\n if not data_home:\n # The freedesktop spec defines the following default directory for\n # when XDG_DATA_HOME is unset or empty. This user-level directory\n # takes precedence over system-level directories.\n data_home = os.path.expanduser("~/.local/share")\n xdg_dirs = [data_home]\n\n data_dirs = os.environ.get("XDG_DATA_DIRS")\n if not data_dirs:\n # Similarly, defaults are defined for the system-level directories\n data_dirs = "/usr/local/share:/usr/share"\n xdg_dirs += data_dirs.split(":")\n\n dirs += [os.path.join(xdg_dir, "fonts") for xdg_dir in xdg_dirs]\n elif sys.platform == "darwin":\n dirs += [\n "/Library/Fonts",\n "/System/Library/Fonts",\n os.path.expanduser("~/Library/Fonts"),\n ]\n\n ext = os.path.splitext(ttf_filename)[1]\n first_font_with_a_different_extension = None\n for directory in dirs:\n for walkroot, walkdir, walkfilenames in os.walk(directory):\n for walkfilename in walkfilenames:\n if ext and walkfilename == ttf_filename:\n return freetype(os.path.join(walkroot, walkfilename))\n elif not ext and os.path.splitext(walkfilename)[0] == ttf_filename:\n fontpath = os.path.join(walkroot, walkfilename)\n if os.path.splitext(fontpath)[1] == ".ttf":\n return freetype(fontpath)\n if not ext and first_font_with_a_different_extension is None:\n first_font_with_a_different_extension = fontpath\n if first_font_with_a_different_extension:\n return freetype(first_font_with_a_different_extension)\n raise\n\n\ndef load_path(filename: str | bytes) -> ImageFont:\n """\n Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a\n bitmap font along the Python path.\n\n :param filename: Name of font file.\n :return: A font object.\n :exception OSError: If the file could not be read.\n """\n if not isinstance(filename, str):\n filename = filename.decode("utf-8")\n for directory in sys.path:\n try:\n return load(os.path.join(directory, filename))\n except OSError:\n pass\n msg = f'cannot find font file "{filename}" in sys.path'\n if os.path.exists(filename):\n msg += f', did you mean ImageFont.load("{filename}") instead?'\n\n raise OSError(msg)\n\n\ndef load_default_imagefont() -> ImageFont:\n f = ImageFont()\n f._load_pilfont_data(\n # courB08\n BytesIO(\n base64.b64decode(\n b"""\nUElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAA//8AAQAAAAAAAAABAAEA\nBgAAAAH/+gADAAAAAQAAAAMABgAGAAAAAf/6AAT//QADAAAABgADAAYAAAAA//kABQABAAYAAAAL\nAAgABgAAAAD/+AAFAAEACwAAABAACQAGAAAAAP/5AAUAAAAQAAAAFQAHAAYAAP////oABQAAABUA\nAAAbAAYABgAAAAH/+QAE//wAGwAAAB4AAwAGAAAAAf/5AAQAAQAeAAAAIQAIAAYAAAAB//kABAAB\nACEAAAAkAAgABgAAAAD/+QAE//0AJAAAACgABAAGAAAAAP/6AAX//wAoAAAALQAFAAYAAAAB//8A\nBAACAC0AAAAwAAMABgAAAAD//AAF//0AMAAAADUAAQAGAAAAAf//AAMAAAA1AAAANwABAAYAAAAB\n//kABQABADcAAAA7AAgABgAAAAD/+QAFAAAAOwAAAEAABwAGAAAAAP/5AAYAAABAAAAARgAHAAYA\nAAAA//kABQAAAEYAAABLAAcABgAAAAD/+QAFAAAASwAAAFAABwAGAAAAAP/5AAYAAABQAAAAVgAH\nAAYAAAAA//kABQAAAFYAAABbAAcABgAAAAD/+QAFAAAAWwAAAGAABwAGAAAAAP/5AAUAAABgAAAA\nZQAHAAYAAAAA//kABQAAAGUAAABqAAcABgAAAAD/+QAFAAAAagAAAG8ABwAGAAAAAf/8AAMAAABv\nAAAAcQAEAAYAAAAA//wAAwACAHEAAAB0AAYABgAAAAD/+gAE//8AdAAAAHgABQAGAAAAAP/7AAT/\n/gB4AAAAfAADAAYAAAAB//oABf//AHwAAACAAAUABgAAAAD/+gAFAAAAgAAAAIUABgAGAAAAAP/5\nAAYAAQCFAAAAiwAIAAYAAP////oABgAAAIsAAACSAAYABgAA////+gAFAAAAkgAAAJgABgAGAAAA\nAP/6AAUAAACYAAAAnQAGAAYAAP////oABQAAAJ0AAACjAAYABgAA////+gAFAAAAowAAAKkABgAG\nAAD////6AAUAAACpAAAArwAGAAYAAAAA//oABQAAAK8AAAC0AAYABgAA////+gAGAAAAtAAAALsA\nBgAGAAAAAP/6AAQAAAC7AAAAvwAGAAYAAP////oABQAAAL8AAADFAAYABgAA////+gAGAAAAxQAA\nAMwABgAGAAD////6AAUAAADMAAAA0gAGAAYAAP////oABQAAANIAAADYAAYABgAA////+gAGAAAA\n2AAAAN8ABgAGAAAAAP/6AAUAAADfAAAA5AAGAAYAAP////oABQAAAOQAAADqAAYABgAAAAD/+gAF\nAAEA6gAAAO8ABwAGAAD////6AAYAAADvAAAA9gAGAAYAAAAA//oABQAAAPYAAAD7AAYABgAA////\n+gAFAAAA+wAAAQEABgAGAAD////6AAYAAAEBAAABCAAGAAYAAP////oABgAAAQgAAAEPAAYABgAA\n////+gAGAAABDwAAARYABgAGAAAAAP/6AAYAAAEWAAABHAAGAAYAAP////oABgAAARwAAAEjAAYA\nBgAAAAD/+gAFAAABIwAAASgABgAGAAAAAf/5AAQAAQEoAAABKwAIAAYAAAAA//kABAABASsAAAEv\nAAgABgAAAAH/+QAEAAEBLwAAATIACAAGAAAAAP/5AAX//AEyAAABNwADAAYAAAAAAAEABgACATcA\nAAE9AAEABgAAAAH/+QAE//wBPQAAAUAAAwAGAAAAAP/7AAYAAAFAAAABRgAFAAYAAP////kABQAA\nAUYAAAFMAAcABgAAAAD/+wAFAAABTAAAAVEABQAGAAAAAP/5AAYAAAFRAAABVwAHAAYAAAAA//sA\nBQAAAVcAAAFcAAUABgAAAAD/+QAFAAABXAAAAWEABwAGAAAAAP/7AAYAAgFhAAABZwAHAAYAAP//\n//kABQAAAWcAAAFtAAcABgAAAAD/+QAGAAABbQAAAXMABwAGAAAAAP/5AAQAAgFzAAABdwAJAAYA\nAP////kABgAAAXcAAAF+AAcABgAAAAD/+QAGAAABfgAAAYQABwAGAAD////7AAUAAAGEAAABigAF\nAAYAAP////sABQAAAYoAAAGQAAUABgAAAAD/+wAFAAABkAAAAZUABQAGAAD////7AAUAAgGVAAAB\nmwAHAAYAAAAA//sABgACAZsAAAGhAAcABgAAAAD/+wAGAAABoQAAAacABQAGAAAAAP/7AAYAAAGn\nAAABrQAFAAYAAAAA//kABgAAAa0AAAGzAAcABgAA////+wAGAAABswAAAboABQAGAAD////7AAUA\nAAG6AAABwAAFAAYAAP////sABgAAAcAAAAHHAAUABgAAAAD/+wAGAAABxwAAAc0ABQAGAAD////7\nAAYAAgHNAAAB1AAHAAYAAAAA//sABQAAAdQAAAHZAAUABgAAAAH/+QAFAAEB2QAAAd0ACAAGAAAA\nAv/6AAMAAQHdAAAB3gAHAAYAAAAA//kABAABAd4AAAHiAAgABgAAAAD/+wAF//0B4gAAAecAAgAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAB\n//sAAwACAecAAAHpAAcABgAAAAD/+QAFAAEB6QAAAe4ACAAGAAAAAP/5AAYAAAHuAAAB9AAHAAYA\nAAAA//oABf//AfQAAAH5AAUABgAAAAD/+QAGAAAB+QAAAf8ABwAGAAAAAv/5AAMAAgH/AAACAAAJ\nAAYAAAAA//kABQABAgAAAAIFAAgABgAAAAH/+gAE//sCBQAAAggAAQAGAAAAAP/5AAYAAAIIAAAC\nDgAHAAYAAAAB//kABf/+Ag4AAAISAAUABgAA////+wAGAAACEgAAAhkABQAGAAAAAP/7AAX//gIZ\nAAACHgADAAYAAAAA//wABf/9Ah4AAAIjAAEABgAAAAD/+QAHAAACIwAAAioABwAGAAAAAP/6AAT/\n+wIqAAACLgABAAYAAAAA//kABP/8Ai4AAAIyAAMABgAAAAD/+gAFAAACMgAAAjcABgAGAAAAAf/5\nAAT//QI3AAACOgAEAAYAAAAB//kABP/9AjoAAAI9AAQABgAAAAL/+QAE//sCPQAAAj8AAgAGAAD/\n///7AAYAAgI/AAACRgAHAAYAAAAA//kABgABAkYAAAJMAAgABgAAAAH//AAD//0CTAAAAk4AAQAG\nAAAAAf//AAQAAgJOAAACUQADAAYAAAAB//kABP/9AlEAAAJUAAQABgAAAAH/+QAF//4CVAAAAlgA\nBQAGAAD////7AAYAAAJYAAACXwAFAAYAAP////kABgAAAl8AAAJmAAcABgAA////+QAGAAACZgAA\nAm0ABwAGAAD////5AAYAAAJtAAACdAAHAAYAAAAA//sABQACAnQAAAJ5AAcABgAA////9wAGAAAC\neQAAAoAACQAGAAD////3AAYAAAKAAAAChwAJAAYAAP////cABgAAAocAAAKOAAkABgAA////9wAG\nAAACjgAAApUACQAGAAD////4AAYAAAKVAAACnAAIAAYAAP////cABgAAApwAAAKjAAkABgAA////\n+gAGAAACowAAAqoABgAGAAAAAP/6AAUAAgKqAAACrwAIAAYAAP////cABQAAAq8AAAK1AAkABgAA\n////9wAFAAACtQAAArsACQAGAAD////3AAUAAAK7AAACwQAJAAYAAP////gABQAAAsEAAALHAAgA\nBgAAAAD/9wAEAAACxwAAAssACQAGAAAAAP/3AAQAAALLAAACzwAJAAYAAAAA//cABAAAAs8AAALT\nAAkABgAAAAD/+AAEAAAC0wAAAtcACAAGAAD////6AAUAAALXAAAC3QAGAAYAAP////cABgAAAt0A\nAALkAAkABgAAAAD/9wAFAAAC5AAAAukACQAGAAAAAP/3AAUAAALpAAAC7gAJAAYAAAAA//cABQAA\nAu4AAALzAAkABgAAAAD/9wAFAAAC8wAAAvgACQAGAAAAAP/4AAUAAAL4AAAC/QAIAAYAAAAA//oA\nBf//Av0AAAMCAAUABgAA////+gAGAAADAgAAAwkABgAGAAD////3AAYAAAMJAAADEAAJAAYAAP//\n//cABgAAAxAAAAMXAAkABgAA////9wAGAAADFwAAAx4ACQAGAAD////4AAYAAAAAAAoABwASAAYA\nAP////cABgAAAAcACgAOABMABgAA////+gAFAAAADgAKABQAEAAGAAD////6AAYAAAAUAAoAGwAQ\nAAYAAAAA//gABgAAABsACgAhABIABgAAAAD/+AAGAAAAIQAKACcAEgAGAAAAAP/4AAYAAAAnAAoA\nLQASAAYAAAAA//gABgAAAC0ACgAzABIABgAAAAD/+QAGAAAAMwAKADkAEQAGAAAAAP/3AAYAAAA5\nAAoAPwATAAYAAP////sABQAAAD8ACgBFAA8ABgAAAAD/+wAFAAIARQAKAEoAEQAGAAAAAP/4AAUA\nAABKAAoATwASAAYAAAAA//gABQAAAE8ACgBUABIABgAAAAD/+AAFAAAAVAAKAFkAEgAGAAAAAP/5\nAAUAAABZAAoAXgARAAYAAAAA//gABgAAAF4ACgBkABIABgAAAAD/+AAGAAAAZAAKAGoAEgAGAAAA\nAP/4AAYAAABqAAoAcAASAAYAAAAA//kABgAAAHAACgB2ABEABgAAAAD/+AAFAAAAdgAKAHsAEgAG\nAAD////4AAYAAAB7AAoAggASAAYAAAAA//gABQAAAIIACgCHABIABgAAAAD/+AAFAAAAhwAKAIwA\nEgAGAAAAAP/4AAUAAACMAAoAkQASAAYAAAAA//gABQAAAJEACgCWABIABgAAAAD/+QAFAAAAlgAK\nAJsAEQAGAAAAAP/6AAX//wCbAAoAoAAPAAYAAAAA//oABQABAKAACgClABEABgAA////+AAGAAAA\npQAKAKwAEgAGAAD////4AAYAAACsAAoAswASAAYAAP////gABgAAALMACgC6ABIABgAA////+QAG\nAAAAugAKAMEAEQAGAAD////4AAYAAgDBAAoAyAAUAAYAAP////kABQACAMgACgDOABMABgAA////\n+QAGAAIAzgAKANUAEw==\n"""\n )\n ),\n Image.open(\n BytesIO(\n base64.b64decode(\n b"""\niVBORw0KGgoAAAANSUhEUgAAAx4AAAAUAQAAAAArMtZoAAAEwElEQVR4nABlAJr/AHVE4czCI/4u\nMc4b7vuds/xzjz5/3/7u/n9vMe7vnfH/9++vPn/xyf5zhxzjt8GHw8+2d83u8x27199/nxuQ6Od9\nM43/5z2I+9n9ZtmDBwMQECDRQw/eQIQohJXxpBCNVE6QCCAAAAD//wBlAJr/AgALyj1t/wINwq0g\nLeNZUworuN1cjTPIzrTX6ofHWeo3v336qPzfEwRmBnHTtf95/fglZK5N0PDgfRTslpGBvz7LFc4F\nIUXBWQGjQ5MGCx34EDFPwXiY4YbYxavpnhHFrk14CDAAAAD//wBlAJr/AgKqRooH2gAgPeggvUAA\nBu2WfgPoAwzRAABAAAAAAACQgLz/3Uv4Gv+gX7BJgDeeGP6AAAD1NMDzKHD7ANWr3loYbxsAD791\nNAADfcoIDyP44K/jv4Y63/Z+t98Ovt+ub4T48LAAAAD//wBlAJr/AuplMlADJAAAAGuAphWpqhMx\nin0A/fRvAYBABPgBwBUgABBQ/sYAyv9g0bCHgOLoGAAAAAAAREAAwI7nr0ArYpow7aX8//9LaP/9\nSjdavWA8ePHeBIKB//81/83ndznOaXx379wAAAD//wBlAJr/AqDxW+D3AABAAbUh/QMnbQag/gAY\nAYDAAACgtgD/gOqAAAB5IA/8AAAk+n9w0AAA8AAAmFRJuPo27ciC0cD5oeW4E7KA/wD3ECMAn2tt\ny8PgwH8AfAxFzC0JzeAMtratAsC/ffwAAAD//wBlAJr/BGKAyCAA4AAAAvgeYTAwHd1kmQF5chkG\nABoMIHcL5xVpTfQbUqzlAAAErwAQBgAAEOClA5D9il08AEh/tUzdCBsXkbgACED+woQg8Si9VeqY\nlODCn7lmF6NhnAEYgAAA/NMIAAAAAAD//2JgjLZgVGBg5Pv/Tvpc8hwGBjYGJADjHDrAwPzAjv/H\n/Wf3PzCwtzcwHmBgYGcwbZz8wHaCAQMDOwMDQ8MCBgYOC3W7mp+f0w+wHOYxO3OG+e376hsMZjk3\nAAAAAP//YmCMY2A4wMAIN5e5gQETPD6AZisDAwMDgzSDAAPjByiHcQMDAwMDg1nOze1lByRu5/47\nc4859311AYNZzg0AAAAA//9iYGDBYihOIIMuwIjGL39/fwffA8b//xv/P2BPtzzHwCBjUQAAAAD/\n/yLFBrIBAAAA//9i1HhcwdhizX7u8NZNzyLbvT97bfrMf/QHI8evOwcSqGUJAAAA//9iYBB81iSw\npEE170Qrg5MIYydHqwdDQRMrAwcVrQAAAAD//2J4x7j9AAMDn8Q/BgYLBoaiAwwMjPdvMDBYM1Tv\noJodAAAAAP//Yqo/83+dxePWlxl3npsel9lvLfPcqlE9725C+acfVLMEAAAA//9i+s9gwCoaaGMR\nevta/58PTEWzr21hufPjA8N+qlnBwAAAAAD//2JiWLci5v1+HmFXDqcnULE/MxgYGBj+f6CaJQAA\nAAD//2Ji2FrkY3iYpYC5qDeGgeEMAwPDvwQBBoYvcTwOVLMEAAAA//9isDBgkP///0EOg9z35v//\nGc/eeW7BwPj5+QGZhANUswMAAAD//2JgqGBgYGBgqEMXlvhMPUsAAAAA//8iYDd1AAAAAP//AwDR\nw7IkEbzhVQAAAABJRU5ErkJggg==\n"""\n )\n )\n ),\n )\n return f\n\n\ndef load_default(size: float | None = None) -> FreeTypeFont | ImageFont:\n """If FreeType support is available, load a version of Aileron Regular,\n https://dotcolon.net/fonts/aileron, with a more limited character set.\n\n Otherwise, load a "better than nothing" font.\n\n .. versionadded:: 1.1.4\n\n :param size: The font size of Aileron Regular.\n\n .. versionadded:: 10.1.0\n\n :return: A font object.\n """\n if isinstance(core, ModuleType) or size is not None:\n return truetype(\n BytesIO(\n base64.b64decode(\n b"""\nAAEAAAAPAIAAAwBwRkZUTYwDlUAAADFoAAAAHEdERUYAqADnAAAo8AAAACRHUE9ThhmITwAAKfgAA\nAduR1NVQnHxefoAACkUAAAA4k9TLzJovoHLAAABeAAAAGBjbWFw5lFQMQAAA6gAAAGqZ2FzcP//AA\nMAACjoAAAACGdseWYmRXoPAAAGQAAAHfhoZWFkE18ayQAAAPwAAAA2aGhlYQboArEAAAE0AAAAJGh\ntdHjjERZ8AAAB2AAAAdBsb2NhuOexrgAABVQAAADqbWF4cAC7AEYAAAFYAAAAIG5hbWUr+h5lAAAk\nOAAAA6Jwb3N0D3oPTQAAJ9wAAAEKAAEAAAABGhxJDqIhXw889QALA+gAAAAA0Bqf2QAAAADhCh2h/\n2r/LgOxAyAAAAAIAAIAAAAAAAAAAQAAA8r/GgAAA7j/av9qA7EAAQAAAAAAAAAAAAAAAAAAAHQAAQ\nAAAHQAQwAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAADAfoBkAAFAAgCigJYAAAASwKKAlgAAAFeADI\nBPgAAAAAFAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABVS1dOAEAAIPsCAwL/GgDIA8oA5iAAAJMAAAAA\nAhICsgAAACAAAwH0AAAAAAAAAU0AAADYAAAA8gA5AVMAVgJEAEYCRAA1AuQAKQKOAEAAsAArATsAZ\nAE7AB4CMABVAkQAUADc/+EBEgAgANwAJQEv//sCRAApAkQAggJEADwCRAAtAkQAIQJEADkCRAArAk\nQAMgJEACwCRAAxANwAJQDc/+ECRABnAkQAUAJEAEQB8wAjA1QANgJ/AB0CcwBkArsALwLFAGQCSwB\nkAjcAZALGAC8C2gBkAQgAZAIgADcCYQBkAj8AZANiAGQCzgBkAuEALwJWAGQC3QAvAmsAZAJJADQC\nZAAiAqoAXgJuACADuAAaAnEAGQJFABMCTwAuATMAYgEv//sBJwAiAkQAUAH0ADIBLAApAhMAJAJjA\nEoCEQAeAmcAHgIlAB4BIgAVAmcAHgJRAEoA7gA+AOn/8wIKAEoA9wBGA1cASgJRAEoCSgAeAmMASg\nJnAB4BSgBKAcsAGAE5ABQCUABCAgIAAQMRAAEB4v/6AgEAAQHOABQBLwBAAPoAYAEvACECRABNA0Y\nAJAItAHgBKgAcAkQAUAEsAHQAygAgAi0AOQD3ADYA9wAWAaEANgGhABYCbAAlAYMAeAGDADkA6/9q\nAhsAFAIKABUB/QAVAAAAAwAAAAMAAAAcAAEAAAAAAKQAAwABAAAAHAAEAIgAAAAeABAAAwAOAH4Aq\nQCrALEAtAC3ALsgGSAdICYgOiBEISL7Av//AAAAIACpAKsAsAC0ALcAuyAYIBwgJiA5IEQhIvsB//\n//4/+5/7j/tP+y/7D/reBR4E/gR+A14CzfTwVxAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAEGAAABAAAAAAAAAAECAAAAAgAAAAAAAAAAAAAAAAAAAAEAAAMEBQYHCAkKCwwNDg8QERIT\nFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMT\nU5PUFFSU1RVVldYWVpbXF1eX2BhAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGQAAA\nAAAAAAYnFmAAAAAABlAAAAAAAAAAAAAAAAAAAAAAAAAAAAY2htAAAAAAAAAABrbGlqAAAAAHAAbm9\nycwBnAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmACYAJgAmAD4AUgCCAMoBCgFO\nAVwBcgGIAaYBvAHKAdYB6AH2AgwCIAJKAogCpgLWAw4DIgNkA5wDugPUA+gD/AQQBEYEogS8BPoFJ\ngVSBWoFgAWwBcoF1gX6BhQGJAZMBmgGiga0BuIHGgdUB2YHkAeiB8AH3AfyCAoIHAgqCDoITghcCG\noIogjSCPoJKglYCXwJwgnqCgIKKApACl4Klgq8CtwLDAs8C1YLjAuyC9oL7gwMDCYMSAxgDKAMrAz\nqDQoNTA1mDYQNoA2uDcAN2g3oDfYODA4iDkoOXA5sDnoOnA7EDvwAAAAFAAAAAAH0ArwAAwAGAAkA\nDAAPAAAxESERAxMhExcRASELARETAfT6qv6syKr+jgFUqsiqArz9RAGLAP/+1P8B/v3VAP8BLP4CA\nP8AAgA5//IAuQKyAAMACwAANyMDMwIyFhQGIiY0oE4MZk84JCQ4JLQB/v3AJDgkJDgAAgBWAeUBPA\nLfAAMABwAAEyMnMxcjJzOmRgpagkYKWgHl+vr6AAAAAAIARgAAAf4CsgAbAB8AAAEHMxUjByM3Iwc\njNyM1MzcjNTM3MwczNzMHMxUrAQczAZgdZXEvOi9bLzovWmYdZXEvOi9bLzovWp9bHlsBn4w429vb\n2ziMONvb29s4jAAAAAMANf+mAg4DDAAfACYALAAAJRQGBxUjNS4BJzMeARcRLgE0Njc1MxUeARcjJ\nicVHgEBFBYXNQ4BExU+ATU0Ag5xWDpgcgRcBz41Xl9oVTpVYwpcC1ttXP6cLTQuM5szOrVRZwlOTQ\nZqVzZECAEAGlukZAlOTQdrUG8O7iNlAQgxNhDlCDj+8/YGOjReAAAAAAUAKf/yArsCvAAHAAsAFQA\ndACcAABIyFhQGIiY0EyMBMwQiBhUUFjI2NTQSMhYUBiImNDYiBhUUFjI2NTR5iFBQiFCVVwHAV/5c\nOiMjOiPmiFBQiFCxOiMjOiMCvFaSVlaS/ZoCsjIzMC80NC8w/uNWklZWkhozMC80NC8wAAAAAgBA/\n/ICbgLAACIALgAAARUjEQYjIiY1NDY3LgE1NDYzMhcVJiMiBhUUFhcWOwE1MxUFFBYzMjc1IyIHDg\nECbmBcYYOOVkg7R4hsQjY4Q0RNRD4SLDxW/pJUXzksPCkUUk0BgUb+zBVUZ0BkDw5RO1huCkULQzp\nCOAMBcHDHRz0J/AIHRQAAAAEAKwHlAIUC3wADAAATIycze0YKWgHl+gAAAAABAGT/sAEXAwwACQAA\nEzMGEBcjLgE0Nt06dXU6OUBAAwzG/jDGVePs4wAAAAEAHv+wANEDDAAJAAATMx4BFAYHIzYQHjo5Q\nEA5OnUDDFXj7ONVxgHQAAAAAQBVAFIB2wHbAA4AAAE3FwcXBycHJzcnNxcnMwEtmxOfcTJjYzJxnx\nObCj4BKD07KYolmZkliik7PbMAAQBQAFUB9AIlAAsAAAEjFSM1IzUzNTMVMwH0tTq1tTq1AR/Kyjj\nOzgAAAAAB/+H/iACMAGQABAAANwcjNzOMWlFOXVrS3AAAAQAgAP8A8gE3AAMAABMjNTPy0tIA/zgA\nAQAl//IApQByAAcAADYyFhQGIiY0STgkJDgkciQ4JCQ4AAAAAf/7/+IBNALQAAMAABcjEzM5Pvs+H\ngLuAAAAAAIAKf/yAhsCwAADAAcAABIgECA2IBAgKQHy/g5gATL+zgLA/TJEAkYAAAAAAQCCAAABlg\nKyAAgAAAERIxEHNTc2MwGWVr6SIygCsv1OAldxW1sWAAEAPAAAAg4CwAAZAAA3IRUhNRM+ATU0JiM\niDwEjNz4BMzIWFRQGB7kBUv4x+kI2QTt+EAFWAQp8aGVtSl5GRjEA/0RVLzlLmAoKa3FsUkNxXQAA\nAAEALf/yAhYCwAAqAAABHgEVFAYjIi8BMxceATMyNjU0KwE1MzI2NTQmIyIGDwEjNz4BMzIWFRQGA\nYxBSZJo2RUBVgEHV0JBUaQREUBUQzc5TQcBVgEKfGhfcEMBbxJbQl1x0AoKRkZHPn9GSD80QUVCCg\npfbGBPOlgAAAACACEAAAIkArIACgAPAAAlIxUjNSE1ATMRMyMRBg8BAiRXVv6qAVZWV60dHLCurq4\nrAdn+QgFLMibzAAABADn/8gIZArIAHQAAATIWFRQGIyIvATMXFjMyNjU0JiMiByMTIRUhBzc2ATNv\nd5Fl1RQBVgIad0VSTkVhL1IwAYj+vh8rMAHHgGdtgcUKCoFXTU5bYgGRRvAuHQAAAAACACv/8gITA\nsAAFwAjAAABMhYVFAYjIhE0NjMyFh8BIycmIyIDNzYTMjY1NCYjIgYVFBYBLmp7imr0l3RZdAgBXA\nIYZ5wKJzU6QVNJSz5SUAHSgWltiQFGxcNlVQoKdv7sPiz+ZF1LTmJbU0lhAAAAAQAyAAACGgKyAAY\nAAAEVASMBITUCGv6oXAFL/oECsij9dgJsRgAAAAMALP/xAhgCwAAWACAALAAAAR4BFRQGIyImNTQ2\nNy4BNTQ2MhYVFAYmIgYVFBYyNjU0AzI2NTQmIyIGFRQWAZQ5S5BmbIpPOjA7ecp5P2F8Q0J8RIVJS\n0pLTEtOAW0TXTxpZ2ZqPF0SE1A3VWVlVTdQ/UU0N0RENzT9/ko+Ok1NOj1LAAIAMf/yAhkCwAAXAC\nMAAAEyERQGIyImLwEzFxYzMhMHBiMiJjU0NhMyNjU0JiMiBhUUFgEl9Jd0WXQIAVwCGGecCic1SWp\n7imo+UlBAQVNJAsD+usXDZVUKCnYBFD4sgWltif5kW1NJYV1LTmIAAAACACX/8gClAiAABwAPAAAS\nMhYUBiImNBIyFhQGIiY0STgkJDgkJDgkJDgkAiAkOCQkOP52JDgkJDgAAAAC/+H/iAClAiAABwAMA\nAASMhYUBiImNBMHIzczSTgkJDgkaFpSTl4CICQ4JCQ4/mba5gAAAQBnAB4B+AH0AAYAAAENARUlNS\nUB+P6qAVb+bwGRAbCmpkbJRMkAAAIAUAC7AfQBuwADAAcAAAEhNSERITUhAfT+XAGk/lwBpAGDOP8\nAOAABAEQAHgHVAfQABgAAARUFNS0BNQHV/m8BVv6qAStEyUSmpkYAAAAAAgAj//IB1ALAABgAIAAA\nATIWFRQHDgEHIz4BNz4BNTQmIyIGByM+ARIyFhQGIiY0AQRibmktIAJWBSEqNig+NTlHBFoDezQ4J\nCQ4JALAZ1BjaS03JS1DMD5LLDQ/SUVgcv2yJDgkJDgAAAAAAgA2/5gDFgKYADYAQgAAAQMGFRQzMj\nY1NCYjIg4CFRQWMzI2NxcGIyImNTQ+AjMyFhUUBiMiJwcGIyImNTQ2MzIfATcHNzYmIyIGFRQzMjY\nCej8EJjJJlnBAfGQ+oHtAhjUYg5OPx0h2k06Os3xRWQsVLjY5VHtdPBwJETcJDyUoOkZEJz8B0f74\nEQ8kZl6EkTFZjVOLlyknMVm1pmCiaTq4lX6CSCknTVRmmR8wPdYnQzxuSWVGAAIAHQAAAncCsgAHA\nAoAACUjByMTMxMjATMDAcj+UVz4dO5d/sjPZPT0ArL9TgE6ATQAAAADAGQAAAJMArIAEAAbACcAAA\nEeARUUBgcGKwERMzIXFhUUJRUzMjc2NTQnJiMTPgE1NCcmKwEVMzIBvkdHZkwiNt7LOSGq/oeFHBt\nhahIlSTM+cB8Yj5UWAW8QT0VYYgwFArIEF5Fv1eMED2NfDAL93AU+N24PBP0AAAAAAQAv//ICjwLA\nABsAAAEyFh8BIycmIyIGFRQWMzI/ATMHDgEjIiY1NDYBdX+PCwFWAiKiaHx5ZaIiAlYBCpWBk6a0A\nsCAagoKpqN/gaOmCgplhcicn8sAAAIAZAAAAp8CsgAMABkAAAEeARUUBgcGKwERMzITPgE1NCYnJi\nsBETMyAY59lJp8IzXN0jUVWmdjWRs5d3I4Aq4QqJWUug8EArL9mQ+PeHGHDgX92gAAAAABAGQAAAI\nvArIACwAAJRUhESEVIRUhFSEVAi/+NQHB/pUBTf6zRkYCskbwRvAAAAABAGQAAAIlArIACQAAExUh\nFSERIxEhFboBQ/69VgHBAmzwRv7KArJGAAAAAAEAL//yAo8CwAAfAAABMxEjNQcGIyImNTQ2MzIWH\nwEjJyYjIgYVFBYzMjY1IwGP90wfPnWTprSSf48LAVYCIqJofHllVG+hAU3+s3hARsicn8uAagoKpq\nN/gaN1XAAAAAEAZAAAAowCsgALAAABESMRIREjETMRIRECjFb+hFZWAXwCsv1OAS7+0gKy/sQBPAA\nAAAABAGQAAAC6ArIAAwAAMyMRM7pWVgKyAAABADf/8gHoArIAEwAAAREUBw4BIyImLwEzFxYzMjc2\nNREB6AIFcGpgbQIBVgIHfXQKAQKy/lYxIltob2EpKYyEFD0BpwAAAAABAGQAAAJ0ArIACwAACQEjA\nwcVIxEzEQEzATsBJ3ntQlZWAVVlAWH+nwEnR+ACsv6RAW8AAQBkAAACLwKyAAUAACUVIREzEQIv/j\nVWRkYCsv2UAAABAGQAAAMUArIAFAAAAREjETQ3BgcDIwMmJxYVESMRMxsBAxRWAiMxemx8NxsCVo7\nMywKy/U4BY7ZLco7+nAFmoFxLtP6dArL9lwJpAAAAAAEAZAAAAoACsgANAAAhIwEWFREjETMBJjUR\nMwKAhP67A1aEAUUDVAJeeov+pwKy/aJ5jAFZAAAAAgAv//ICuwLAAAkAEwAAEiAWFRQGICY1NBIyN\njU0JiIGFRTbATSsrP7MrNrYenrYegLAxaKhxsahov47nIeIm5uIhwACAGQAAAJHArIADgAYAAABHg\nEVFAYHBisBESMRMzITNjQnJisBETMyAZRUX2VOHzuAVtY7GlxcGDWIiDUCrgtnVlVpCgT+5gKy/rU\nV1BUF/vgAAAACAC//zAK9AsAAEgAcAAAlFhcHJiMiBwYjIiY1NDYgFhUUJRQWMjY1NCYiBgI9PUMx\nUDcfKh8omqysATSs/dR62Hp62HpICTg7NgkHxqGixcWitbWHnJyHiJubAAIAZAAAAlgCsgAXACMAA\nCUWFyMmJyYnJisBESMRMzIXHgEVFAYHFiUzMjc+ATU0JyYrAQIqDCJfGQwNWhAhglbiOx9QXEY1Tv\n6bhDATMj1lGSyMtYgtOXR0BwH+1wKyBApbU0BSESRAAgVAOGoQBAABADT/8gIoAsAAJQAAATIWFyM\nuASMiBhUUFhceARUUBiMiJiczHgEzMjY1NCYnLgE1NDYBOmd2ClwGS0E6SUNRdW+HZnKKC1wPWkQ9\nUk1cZGuEAsBwXUJHNjQ3OhIbZVZZbm5kREo+NT5DFRdYUFdrAAAAAAEAIgAAAmQCsgAHAAABIxEjE\nSM1IQJk9lb2AkICbP2UAmxGAAEAXv/yAmQCsgAXAAABERQHDgEiJicmNREzERQXHgEyNjc2NRECZA\nIIgfCBCAJWAgZYmlgGAgKy/k0qFFxzc1wUKgGz/lUrEkRQUEQSKwGrAAAAAAEAIAAAAnoCsgAGAAA\nhIwMzGwEzAYJ07l3N1FwCsv2PAnEAAAEAGgAAA7ECsgAMAAABAyMLASMDMxsBMxsBA7HAcZyicrZi\nkaB0nJkCsv1OAlP9rQKy/ZsCW/2kAmYAAAEAGQAAAm8CsgALAAAhCwEjEwMzGwEzAxMCCsrEY/bkY\nre+Y/D6AST+3AFcAVb+5gEa/q3+oQAAAQATAAACUQKyAAgAAAERIxEDMxsBMwFdVvRjwLphARD+8A\nEQAaL+sQFPAAABAC4AAAI5ArIACQAAJRUhNQEhNSEVAQI5/fUBof57Aen+YUZGQgIqRkX92QAAAAA\nBAGL/sAEFAwwABwAAARUjETMVIxEBBWlpowMMOP0UOANcAAAB//v/4gE0AtAAAwAABSMDMwE0Pvs+\nHgLuAAAAAQAi/7AAxQMMAAcAABcjNTMRIzUzxaNpaaNQOALsOAABAFAA1wH0AmgABgAAJQsBIxMzE\nwGwjY1GsESw1wFZ/qcBkf5vAAAAAQAy/6oBwv/iAAMAAAUhNSEBwv5wAZBWOAAAAAEAKQJEALYCsg\nADAAATIycztjhVUAJEbgAAAAACACT/8gHQAiAAHQAlAAAhJwcGIyImNTQ2OwE1NCcmIyIHIz4BMzI\nXFh0BFBcnMjY9ASYVFAF6CR0wVUtgkJoiAgdgaQlaBm1Zrg4DCuQ9R+5MOSFQR1tbDiwUUXBUXowf\nJ8c9SjRORzYSgVwAAAAAAgBK//ICRQLfABEAHgAAATIWFRQGIyImLwEVIxEzETc2EzI2NTQmIyIGH\nQEUFgFUcYCVbiNJEyNWVigySElcU01JXmECIJd4i5QTEDRJAt/+3jkq/hRuZV55ZWsdX14AAQAe//\nIB9wIgABgAAAEyFhcjJiMiBhUUFjMyNjczDgEjIiY1NDYBF152DFocbEJXU0A1Rw1aE3pbaoKQAiB\noWH5qZm1tPDlaXYuLgZcAAAACAB7/8gIZAt8AEQAeAAABESM1BwYjIiY1NDYzMhYfAREDMjY9ATQm\nIyIGFRQWAhlWKDJacYCVbiNJEyOnSV5hQUlcUwLf/SFVOSqXeIuUExA0ARb9VWVrHV9ebmVeeQACA\nB7/8gH9AiAAFQAbAAABFAchHgEzMjY3Mw4BIyImNTQ2MzIWJyIGByEmAf0C/oAGUkA1SwlaD4FXbI\nWObmt45UBVBwEqDQEYFhNjWD84W16Oh3+akU9aU60AAAEAFQAAARoC8gAWAAATBh0BMxUjESMRIzU\nzNTQ3PgEzMhcVJqcDbW1WOTkDB0k8Hx5oAngVITRC/jQBzEIsJRs5PwVHEwAAAAIAHv8uAhkCIAAi\nAC8AAAERFAcOASMiLwEzFx4BMzI2NzY9AQcGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZAQSEd\nNwRAVcBBU5DTlUDASgyWnGAlW4jSRMjp0leYUFJXFMCEv5wSh1zeq8KCTI8VU0ZIQk5Kpd4i5QTED\nRJ/iJlax1fXm5lXnkAAQBKAAACCgLkABcAAAEWFREjETQnLgEHDgEdASMRMxE3NjMyFgIIAlYCBDs\n6RVRWViE5UVViAYUbQP7WASQxGzI7AQJyf+kC5P7TPSxUAAACAD4AAACsAsAABwALAAASMhYUBiIm\nNBMjETNeLiAgLiBiVlYCwCAuICAu/WACEgAC//P/LgCnAsAABwAVAAASMhYUBiImNBcRFAcGIyInN\nRY3NjURWS4gIC4gYgMLcRwNSgYCAsAgLiAgLo79wCUbZAJGBzMOHgJEAAAAAQBKAAACCALfAAsAAC\nEnBxUjETMREzMHEwGTwTJWVvdu9/rgN6kC3/4oAQv6/ugAAQBG//wA3gLfAA8AABMRFBceATcVBiM\niJicmNRGcAQIcIxkkKi4CAQLf/bkhERoSBD4EJC8SNAJKAAAAAQBKAAADEAIgACQAAAEWFREjETQn\nJiMiFREjETQnJiMiFREjETMVNzYzMhYXNzYzMhYDCwVWBAxedFYEDF50VlYiJko7ThAvJkpEVAGfI\njn+vAEcQyRZ1v76ARxDJFnW/voCEk08HzYtRB9HAAAAAAEASgAAAgoCIAAWAAABFhURIxE0JyYjIg\nYdASMRMxU3NjMyFgIIAlYCCXBEVVZWITlRVWIBhRtA/tYBJDEbbHR/6QISWz0sVAAAAAACAB7/8gI\nsAiAABwARAAASIBYUBiAmNBIyNjU0JiIGFRSlAQCHh/8Ah7ieWlqeWgIgn/Cfn/D+s3ZfYHV1YF8A\nAgBK/zwCRQIgABEAHgAAATIWFRQGIyImLwERIxEzFTc2EzI2NTQmIyIGHQEUFgFUcYCVbiNJEyNWV\nigySElcU01JXmECIJd4i5QTEDT+8wLWVTkq/hRuZV55ZWsdX14AAgAe/zwCGQIgABEAHgAAAREjEQ\ncGIyImNTQ2MzIWHwE1AzI2PQE0JiMiBhUUFgIZVigyWnGAlW4jSRMjp0leYUFJXFMCEv0qARk5Kpd\n4i5QTEDRJ/iJlax1fXm5lXnkAAQBKAAABPgIeAA0AAAEyFxUmBhURIxEzFTc2ARoWDkdXVlYwIwIe\nB0EFVlf+0gISU0cYAAEAGP/yAa0CIAAjAAATMhYXIyYjIgYVFBYXHgEVFAYjIiYnMxYzMjY1NCYnL\ngE1NDbkV2MJWhNdKy04PF1XbVhWbgxaE2ktOjlEUllkAiBaS2MrJCUoEBlPQkhOVFZoKCUmLhIWSE\nBIUwAAAAEAFP/4ARQCiQAXAAATERQXHgE3FQYjIiYnJjURIzUzNTMVMxWxAQMmMx8qMjMEAUdHVmM\nBzP7PGw4mFgY/BSwxDjQBNUJ7e0IAAAABAEL/8gICAhIAFwAAAREjNQcGIyImJyY1ETMRFBceATMy\nNj0BAgJWITlRT2EKBVYEBkA1RFECEv3uWj4qTToiOQE+/tIlJC43c4DpAAAAAAEAAQAAAfwCEgAGA\nAABAyMDMxsBAfzJaclfop8CEv3uAhL+LQHTAAABAAEAAAMLAhIADAAAAQMjCwEjAzMbATMbAQMLqW\nZ2dmapY3t0a3Z7AhL97gG+/kICEv5AAcD+QwG9AAAB//oAAAHWAhIACwAAARMjJwcjEwMzFzczARq\n8ZIuKY763ZoWFYwEO/vLV1QEMAQbNzQAAAQAB/y4B+wISABEAAAEDDgEjIic1FjMyNj8BAzMbAQH7\n2iFZQB8NDRIpNhQH02GenQIS/cFVUAJGASozEwIt/i4B0gABABQAAAGxAg4ACQAAJRUhNQEhNSEVA\nQGx/mMBNP7iAYL+zkREQgGIREX+ewAAAAABAED/sAEOAwwALAAAASMiBhUUFxYVFAYHHgEVFAcGFR\nQWOwEVIyImNTQ3NjU0JzU2NTQnJjU0NjsBAQ4MKiMLDS4pKS4NCyMqDAtERAwLUlILDERECwLUGBk\nWTlsgKzUFBTcrIFtOFhkYOC87GFVMIkUIOAhFIkxVGDsvAAAAAAEAYP84AJoDIAADAAAXIxEzmjo6\nyAPoAAEAIf+wAO8DDAAsAAATFQYVFBcWFRQGKwE1MzI2NTQnJjU0NjcuATU0NzY1NCYrATUzMhYVF\nAcGFRTvUgsMREQLDCojCw0uKSkuDQsjKgwLREQMCwF6OAhFIkxVGDsvOBgZFk5bICs1BQU3KyBbTh\nYZGDgvOxhVTCJFAAABAE0A3wH2AWQAEwAAATMUIyImJyYjIhUjNDMyFhcWMzIBvjhuGywtQR0xOG4\nbLC1BHTEBZIURGCNMhREYIwAAAwAk/94DIgLoAAcAEQApAAAAIBYQBiAmECQgBhUUFiA2NTQlMhYX\nIyYjIgYUFjMyNjczDgEjIiY1NDYBAQFE3d3+vN0CB/7wubkBELn+xVBnD1wSWDo+QTcqOQZcEmZWX\nHN2Aujg/rbg4AFKpr+Mjb6+jYxbWEldV5ZZNShLVn5na34AAgB4AFIB9AGeAAUACwAAAQcXIyc3Mw\ncXIyc3AUqJiUmJifOJiUmJiQGepqampqampqYAAAIAHAHSAQ4CwAAHAA8AABIyFhQGIiY0NiIGFBY\nyNjRgakREakSTNCEhNCECwEJqQkJqCiM4IyM4AAAAAAIAUAAAAfQCCwALAA8AAAEzFSMVIzUjNTM1\nMxMhNSEBP7W1OrW1OrX+XAGkAVs4tLQ4sP31OAAAAQB0AkQBAQKyAAMAABMjNzOsOD1QAkRuAAAAA\nAEAIADsAKoBdgAHAAASMhYUBiImNEg6KCg6KAF2KDooKDoAAAIAOQBSAbUBngAFAAsAACUHIzcnMw\nUHIzcnMwELiUmJiUkBM4lJiYlJ+KampqampqYAAAABADYB5QDhAt8ABAAAEzczByM2Xk1OXQHv8Po\nAAQAWAeUAwQLfAAQAABMHIzczwV5NTl0C1fD6AAIANgHlAYsC3wAEAAkAABM3MwcjPwEzByM2Xk1O\nXapeTU5dAe/w+grw+gAAAgAWAeUBawLfAAQACQAAEwcjNzMXByM3M8FeTU5dql5NTl0C1fD6CvD6A\nAADACX/8gI1AHIABwAPABcAADYyFhQGIiY0NjIWFAYiJjQ2MhYUBiImNEk4JCQ4JOw4JCQ4JOw4JC\nQ4JHIkOCQkOCQkOCQkOCQkOCQkOAAAAAEAeABSAUoBngAFAAABBxcjJzcBSomJSYmJAZ6mpqamAAA\nAAAEAOQBSAQsBngAFAAAlByM3JzMBC4lJiYlJ+KampgAAAf9qAAABgQKyAAMAACsBATM/VwHAVwKy\nAAAAAAIAFAHIAdwClAAHABQAABMVIxUjNSM1BRUjNwcjJxcjNTMXN9pKMkoByDICKzQqATJLKysCl\nCmjoykBy46KiY3Lm5sAAQAVAAABvALyABgAAAERIxEjESMRIzUzNTQ3NjMyFxUmBgcGHQEBvFbCVj\nk5AxHHHx5iVgcDAg798gHM/jQBzEIOJRuWBUcIJDAVIRYAAAABABX//AHkAvIAJQAAJR4BNxUGIyI\nmJyY1ESYjIgcGHQEzFSMRIxEjNTM1NDc2MzIXERQBowIcIxkkKi4CAR4nXgwDbW1WLy8DEbNdOmYa\nEQQ/BCQvEjQCFQZWFSEWQv40AcxCDiUblhP9uSEAAAAAAAAWAQ4AAQAAAAAAAAATACgAAQAAAAAAA\nQAHAEwAAQAAAAAAAgAHAGQAAQAAAAAAAwAaAKIAAQAAAAAABAAHAM0AAQAAAAAABQA8AU8AAQAAAA\nAABgAPAawAAQAAAAAACAALAdQAAQAAAAAACQALAfgAAQAAAAAACwAXAjQAAQAAAAAADAAXAnwAAwA\nBBAkAAAAmAAAAAwABBAkAAQAOADwAAwABBAkAAgAOAFQAAwABBAkAAwA0AGwAAwABBAkABAAOAL0A\nAwABBAkABQB4ANUAAwABBAkABgAeAYwAAwABBAkACAAWAbwAAwABBAkACQAWAeAAAwABBAkACwAuA\ngQAAwABBAkADAAuAkwATgBvACAAUgBpAGcAaAB0AHMAIABSAGUAcwBlAHIAdgBlAGQALgAATm8gUm\nlnaHRzIFJlc2VydmVkLgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAUgBlAGcAdQBsAGEAcgAAUmV\nndWxhcgAAMQAuADEAMAAyADsAVQBLAFcATgA7AEEAaQBsAGUAcgBvAG4ALQBSAGUAZwB1AGwAYQBy\nAAAxLjEwMjtVS1dOO0FpbGVyb24tUmVndWxhcgAAQQBpAGwAZQByAG8AbgAAQWlsZXJvbgAAVgBlA\nHIAcwBpAG8AbgAgADEALgAxADAAMgA7AFAAUwAgADAAMAAxAC4AMQAwADIAOwBoAG8AdABjAG8Abg\nB2ACAAMQAuADAALgA3ADAAOwBtAGEAawBlAG8AdABmAC4AbABpAGIAMgAuADUALgA1ADgAMwAyADk\nAAFZlcnNpb24gMS4xMDI7UFMgMDAxLjEwMjtob3Rjb252IDEuMC43MDttYWtlb3RmLmxpYjIuNS41\nODMyOQAAQQBpAGwAZQByAG8AbgAtAFIAZQBnAHUAbABhAHIAAEFpbGVyb24tUmVndWxhcgAAUwBvA\nHIAYQAgAFMAYQBnAGEAbgBvAABTb3JhIFNhZ2FubwAAUwBvAHIAYQAgAFMAYQBnAGEAbgBvAABTb3\nJhIFNhZ2FubwAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBsAG8AbgAuAG4AZQB0AAB\nodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAaAB0AHQAcAA6AC8ALwB3AHcAdwAuAGQAbwB0AGMAbwBs\nAG8AbgAuAG4AZQB0AABodHRwOi8vd3d3LmRvdGNvbG9uLm5ldAAAAAACAAAAAAAA/4MAMgAAAAAAA\nAAAAAAAAAAAAAAAAAAAAHQAAAABAAIAAwAEAAUABgAHAAgACQAKAAsADAANAA4ADwAQABEAEgATAB\nQAFQAWABcAGAAZABoAGwAcAB0AHgAfACAAIQAiACMAJAAlACYAJwAoACkAKgArACwALQAuAC8AMAA\nxADIAMwA0ADUANgA3ADgAOQA6ADsAPAA9AD4APwBAAEEAQgBDAEQARQBGAEcASABJAEoASwBMAE0A\nTgBPAFAAUQBSAFMAVABVAFYAVwBYAFkAWgBbAFwAXQBeAF8AYABhAIsAqQCDAJMAjQDDAKoAtgC3A\nLQAtQCrAL4AvwC8AIwAwADBAAAAAAAB//8AAgABAAAADAAAABwAAAACAAIAAwBxAAEAcgBzAAIABA\nAAAAIAAAABAAAACgBMAGYAAkRGTFQADmxhdG4AGgAEAAAAAP//AAEAAAAWAANDQVQgAB5NT0wgABZ\nST00gABYAAP//AAEAAAAA//8AAgAAAAEAAmxpZ2EADmxvY2wAFAAAAAEAAQAAAAEAAAACAAYAEAAG\nAAAAAgASADQABAAAAAEATAADAAAAAgAQABYAAQAcAAAAAQABAE8AAQABAGcAAQABAE8AAwAAAAIAE\nAAWAAEAHAAAAAEAAQAvAAEAAQBnAAEAAQAvAAEAGgABAAgAAgAGAAwAcwACAE8AcgACAEwAAQABAE\nkAAAABAAAACgBGAGAAAkRGTFQADmxhdG4AHAAEAAAAAP//AAIAAAABABYAA0NBVCAAFk1PTCAAFlJ\nPTSAAFgAA//8AAgAAAAEAAmNwc3AADmtlcm4AFAAAAAEAAAAAAAEAAQACAAYADgABAAAAAQASAAIA\nAAACAB4ANgABAAoABQAFAAoAAgABACQAPQAAAAEAEgAEAAAAAQAMAAEAOP/nAAEAAQAkAAIGigAEA\nAAFJAXKABoAGQAA//gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAD/sv+4/+z/7v/MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAD/xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/9T/6AAAAAD/8QAA\nABD/vQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/7gAAAAAAAAAAAAAAAAAA//MAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABIAAAAAAAAAAP/5AAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/gAAD/4AAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//L/9AAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAA/+gAAAAAAAkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/zAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/mAAAAAAAAAAAAAAAAAAD\n/4gAA//AAAAAA//YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/+AAAAAAAAP/OAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/zv/qAAAAAP/0AAAACAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP/ZAAD/egAA/1kAAAAA/5D/rgAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAD/9AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAD/8AAA/7b/8P+wAAD/8P/E/98AAAAA/8P/+P/0//oAAAAAAAAAAAAA//gA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+AAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/w//C/9MAAP/SAAD/9wAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/yAAA/+kAAAAA//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/9wAAAAD//QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAP/2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAP/cAAAAAAAAAAAAAAAA/7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAP/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/6AAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAkAFAAEAAAAAQACwAAABcA\nBgAAAAAAAAAIAA4AAAAAAAsAEgAAAAAAAAATABkAAwANAAAAAQAJAAAAAAAAAAAAAAAAAAAAGAAAA\nAAABwAAAAAAAAAAAAAAFQAFAAAAAAAYABgAAAAUAAAACgAAAAwAAgAPABEAFgAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAEAEQBdAAYAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAcAAAAAAAAABwAAAAAACAAAAAAAAAAAAAcAAAAHAAAAEwAJ\nABUADgAPAAAACwAQAAAAAAAAAAAAAAAAAAUAGAACAAIAAgAAAAIAGAAXAAAAGAAAABYAFgACABYAA\ngAWAAAAEQADAAoAFAAMAA0ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAAAEgAGAAEAHgAkAC\nYAJwApACoALQAuAC8AMgAzADcAOAA5ADoAPAA9AEUASABOAE8AUgBTAFUAVwBZAFoAWwBcAF0AcwA\nAAAAAAQAAAADa3tfFAAAAANAan9kAAAAA4QodoQ==\n"""\n )\n ),\n 10 if size is None else size,\n layout_engine=Layout.BASIC,\n )\n return load_default_imagefont()\n | .venv\Lib\site-packages\PIL\ImageFont.py | ImageFont.py | Python | 65,631 | 0.75 | 0.120239 | 0.073883 | awesome-app | 939 | 2024-01-18T20:40:49.483104 | Apache-2.0 | false | dbebcc7549982a47b650ceeb671332cb |
#\n# The Python Imaging Library\n# $Id$\n#\n# screen grabber\n#\n# History:\n# 2001-04-26 fl created\n# 2001-09-17 fl use builtin driver, if present\n# 2002-11-19 fl added grabclipboard support\n#\n# Copyright (c) 2001-2002 by Secret Labs AB\n# Copyright (c) 2001-2002 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\nfrom . import Image\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from . import ImageWin\n\n\ndef grab(\n bbox: tuple[int, int, int, int] | None = None,\n include_layered_windows: bool = False,\n all_screens: bool = False,\n xdisplay: str | None = None,\n window: int | ImageWin.HWND | None = None,\n) -> Image.Image:\n im: Image.Image\n if xdisplay is None:\n if sys.platform == "darwin":\n fh, filepath = tempfile.mkstemp(".png")\n os.close(fh)\n args = ["screencapture"]\n if bbox:\n left, top, right, bottom = bbox\n args += ["-R", f"{left},{top},{right-left},{bottom-top}"]\n subprocess.call(args + ["-x", filepath])\n im = Image.open(filepath)\n im.load()\n os.unlink(filepath)\n if bbox:\n im_resized = im.resize((right - left, bottom - top))\n im.close()\n return im_resized\n return im\n elif sys.platform == "win32":\n if window is not None:\n all_screens = -1\n offset, size, data = Image.core.grabscreen_win32(\n include_layered_windows,\n all_screens,\n int(window) if window is not None else 0,\n )\n im = Image.frombytes(\n "RGB",\n size,\n data,\n # RGB, 32-bit line padding, origin lower left corner\n "raw",\n "BGR",\n (size[0] * 3 + 3) & -4,\n -1,\n )\n if bbox:\n x0, y0 = offset\n left, top, right, bottom = bbox\n im = im.crop((left - x0, top - y0, right - x0, bottom - y0))\n return im\n # Cast to Optional[str] needed for Windows and macOS.\n display_name: str | None = xdisplay\n try:\n if not Image.core.HAVE_XCB:\n msg = "Pillow was built without XCB support"\n raise OSError(msg)\n size, data = Image.core.grabscreen_x11(display_name)\n except OSError:\n if display_name is None and sys.platform not in ("darwin", "win32"):\n if shutil.which("gnome-screenshot"):\n args = ["gnome-screenshot", "-f"]\n elif shutil.which("grim"):\n args = ["grim"]\n elif shutil.which("spectacle"):\n args = ["spectacle", "-n", "-b", "-f", "-o"]\n else:\n raise\n fh, filepath = tempfile.mkstemp(".png")\n os.close(fh)\n subprocess.call(args + [filepath])\n im = Image.open(filepath)\n im.load()\n os.unlink(filepath)\n if bbox:\n im_cropped = im.crop(bbox)\n im.close()\n return im_cropped\n return im\n else:\n raise\n else:\n im = Image.frombytes("RGB", size, data, "raw", "BGRX", size[0] * 4, 1)\n if bbox:\n im = im.crop(bbox)\n return im\n\n\ndef grabclipboard() -> Image.Image | list[str] | None:\n if sys.platform == "darwin":\n p = subprocess.run(\n ["osascript", "-e", "get the clipboard as «class PNGf»"],\n capture_output=True,\n )\n if p.returncode != 0:\n return None\n\n import binascii\n\n data = io.BytesIO(binascii.unhexlify(p.stdout[11:-3]))\n return Image.open(data)\n elif sys.platform == "win32":\n fmt, data = Image.core.grabclipboard_win32()\n if fmt == "file": # CF_HDROP\n import struct\n\n o = struct.unpack_from("I", data)[0]\n if data[16] == 0:\n files = data[o:].decode("mbcs").split("\0")\n else:\n files = data[o:].decode("utf-16le").split("\0")\n return files[: files.index("")]\n if isinstance(data, bytes):\n data = io.BytesIO(data)\n if fmt == "png":\n from . import PngImagePlugin\n\n return PngImagePlugin.PngImageFile(data)\n elif fmt == "DIB":\n from . import BmpImagePlugin\n\n return BmpImagePlugin.DibImageFile(data)\n return None\n else:\n if os.getenv("WAYLAND_DISPLAY"):\n session_type = "wayland"\n elif os.getenv("DISPLAY"):\n session_type = "x11"\n else: # Session type check failed\n session_type = None\n\n if shutil.which("wl-paste") and session_type in ("wayland", None):\n args = ["wl-paste", "-t", "image"]\n elif shutil.which("xclip") and session_type in ("x11", None):\n args = ["xclip", "-selection", "clipboard", "-t", "image/png", "-o"]\n else:\n msg = "wl-paste or xclip is required for ImageGrab.grabclipboard() on Linux"\n raise NotImplementedError(msg)\n\n p = subprocess.run(args, capture_output=True)\n if p.returncode != 0:\n err = p.stderr\n for silent_error in [\n # wl-paste, when the clipboard is empty\n b"Nothing is copied",\n # Ubuntu/Debian wl-paste, when the clipboard is empty\n b"No selection",\n # Ubuntu/Debian wl-paste, when an image isn't available\n b"No suitable type of content copied",\n # wl-paste or Ubuntu/Debian xclip, when an image isn't available\n b" not available",\n # xclip, when an image isn't available\n b"cannot convert ",\n # xclip, when the clipboard isn't initialized\n b"xclip: Error: There is no owner for the ",\n ]:\n if silent_error in err:\n return None\n msg = f"{args[0]} error"\n if err:\n msg += f": {err.strip().decode()}"\n raise ChildProcessError(msg)\n\n data = io.BytesIO(p.stdout)\n im = Image.open(data)\n im.load()\n return im\n | .venv\Lib\site-packages\PIL\ImageGrab.py | ImageGrab.py | Python | 6,667 | 0.95 | 0.173469 | 0.132597 | python-kit | 570 | 2024-04-14T17:22:28.719644 | GPL-3.0 | false | 747b1237bbaa1da8a306debda9d4f30b |
#\n# The Python Imaging Library\n# $Id$\n#\n# a simple math add-on for the Python Imaging Library\n#\n# History:\n# 1999-02-15 fl Original PIL Plus release\n# 2005-05-05 fl Simplified and cleaned up for PIL 1.1.6\n# 2005-09-12 fl Fixed int() and float() for Python 2.4.1\n#\n# Copyright (c) 1999-2005 by Secret Labs AB\n# Copyright (c) 2005 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport builtins\nfrom types import CodeType\nfrom typing import Any, Callable\n\nfrom . import Image, _imagingmath\nfrom ._deprecate import deprecate\n\n\nclass _Operand:\n """Wraps an image operand, providing standard operators"""\n\n def __init__(self, im: Image.Image):\n self.im = im\n\n def __fixup(self, im1: _Operand | float) -> Image.Image:\n # convert image to suitable mode\n if isinstance(im1, _Operand):\n # argument was an image.\n if im1.im.mode in ("1", "L"):\n return im1.im.convert("I")\n elif im1.im.mode in ("I", "F"):\n return im1.im\n else:\n msg = f"unsupported mode: {im1.im.mode}"\n raise ValueError(msg)\n else:\n # argument was a constant\n if isinstance(im1, (int, float)) and self.im.mode in ("1", "L", "I"):\n return Image.new("I", self.im.size, im1)\n else:\n return Image.new("F", self.im.size, im1)\n\n def apply(\n self,\n op: str,\n im1: _Operand | float,\n im2: _Operand | float | None = None,\n mode: str | None = None,\n ) -> _Operand:\n im_1 = self.__fixup(im1)\n if im2 is None:\n # unary operation\n out = Image.new(mode or im_1.mode, im_1.size, None)\n try:\n op = getattr(_imagingmath, f"{op}_{im_1.mode}")\n except AttributeError as e:\n msg = f"bad operand type for '{op}'"\n raise TypeError(msg) from e\n _imagingmath.unop(op, out.getim(), im_1.getim())\n else:\n # binary operation\n im_2 = self.__fixup(im2)\n if im_1.mode != im_2.mode:\n # convert both arguments to floating point\n if im_1.mode != "F":\n im_1 = im_1.convert("F")\n if im_2.mode != "F":\n im_2 = im_2.convert("F")\n if im_1.size != im_2.size:\n # crop both arguments to a common size\n size = (\n min(im_1.size[0], im_2.size[0]),\n min(im_1.size[1], im_2.size[1]),\n )\n if im_1.size != size:\n im_1 = im_1.crop((0, 0) + size)\n if im_2.size != size:\n im_2 = im_2.crop((0, 0) + size)\n out = Image.new(mode or im_1.mode, im_1.size, None)\n try:\n op = getattr(_imagingmath, f"{op}_{im_1.mode}")\n except AttributeError as e:\n msg = f"bad operand type for '{op}'"\n raise TypeError(msg) from e\n _imagingmath.binop(op, out.getim(), im_1.getim(), im_2.getim())\n return _Operand(out)\n\n # unary operators\n def __bool__(self) -> bool:\n # an image is "true" if it contains at least one non-zero pixel\n return self.im.getbbox() is not None\n\n def __abs__(self) -> _Operand:\n return self.apply("abs", self)\n\n def __pos__(self) -> _Operand:\n return self\n\n def __neg__(self) -> _Operand:\n return self.apply("neg", self)\n\n # binary operators\n def __add__(self, other: _Operand | float) -> _Operand:\n return self.apply("add", self, other)\n\n def __radd__(self, other: _Operand | float) -> _Operand:\n return self.apply("add", other, self)\n\n def __sub__(self, other: _Operand | float) -> _Operand:\n return self.apply("sub", self, other)\n\n def __rsub__(self, other: _Operand | float) -> _Operand:\n return self.apply("sub", other, self)\n\n def __mul__(self, other: _Operand | float) -> _Operand:\n return self.apply("mul", self, other)\n\n def __rmul__(self, other: _Operand | float) -> _Operand:\n return self.apply("mul", other, self)\n\n def __truediv__(self, other: _Operand | float) -> _Operand:\n return self.apply("div", self, other)\n\n def __rtruediv__(self, other: _Operand | float) -> _Operand:\n return self.apply("div", other, self)\n\n def __mod__(self, other: _Operand | float) -> _Operand:\n return self.apply("mod", self, other)\n\n def __rmod__(self, other: _Operand | float) -> _Operand:\n return self.apply("mod", other, self)\n\n def __pow__(self, other: _Operand | float) -> _Operand:\n return self.apply("pow", self, other)\n\n def __rpow__(self, other: _Operand | float) -> _Operand:\n return self.apply("pow", other, self)\n\n # bitwise\n def __invert__(self) -> _Operand:\n return self.apply("invert", self)\n\n def __and__(self, other: _Operand | float) -> _Operand:\n return self.apply("and", self, other)\n\n def __rand__(self, other: _Operand | float) -> _Operand:\n return self.apply("and", other, self)\n\n def __or__(self, other: _Operand | float) -> _Operand:\n return self.apply("or", self, other)\n\n def __ror__(self, other: _Operand | float) -> _Operand:\n return self.apply("or", other, self)\n\n def __xor__(self, other: _Operand | float) -> _Operand:\n return self.apply("xor", self, other)\n\n def __rxor__(self, other: _Operand | float) -> _Operand:\n return self.apply("xor", other, self)\n\n def __lshift__(self, other: _Operand | float) -> _Operand:\n return self.apply("lshift", self, other)\n\n def __rshift__(self, other: _Operand | float) -> _Operand:\n return self.apply("rshift", self, other)\n\n # logical\n def __eq__(self, other: _Operand | float) -> _Operand: # type: ignore[override]\n return self.apply("eq", self, other)\n\n def __ne__(self, other: _Operand | float) -> _Operand: # type: ignore[override]\n return self.apply("ne", self, other)\n\n def __lt__(self, other: _Operand | float) -> _Operand:\n return self.apply("lt", self, other)\n\n def __le__(self, other: _Operand | float) -> _Operand:\n return self.apply("le", self, other)\n\n def __gt__(self, other: _Operand | float) -> _Operand:\n return self.apply("gt", self, other)\n\n def __ge__(self, other: _Operand | float) -> _Operand:\n return self.apply("ge", self, other)\n\n\n# conversions\ndef imagemath_int(self: _Operand) -> _Operand:\n return _Operand(self.im.convert("I"))\n\n\ndef imagemath_float(self: _Operand) -> _Operand:\n return _Operand(self.im.convert("F"))\n\n\n# logical\ndef imagemath_equal(self: _Operand, other: _Operand | float | None) -> _Operand:\n return self.apply("eq", self, other, mode="I")\n\n\ndef imagemath_notequal(self: _Operand, other: _Operand | float | None) -> _Operand:\n return self.apply("ne", self, other, mode="I")\n\n\ndef imagemath_min(self: _Operand, other: _Operand | float | None) -> _Operand:\n return self.apply("min", self, other)\n\n\ndef imagemath_max(self: _Operand, other: _Operand | float | None) -> _Operand:\n return self.apply("max", self, other)\n\n\ndef imagemath_convert(self: _Operand, mode: str) -> _Operand:\n return _Operand(self.im.convert(mode))\n\n\nops = {\n "int": imagemath_int,\n "float": imagemath_float,\n "equal": imagemath_equal,\n "notequal": imagemath_notequal,\n "min": imagemath_min,\n "max": imagemath_max,\n "convert": imagemath_convert,\n}\n\n\ndef lambda_eval(\n expression: Callable[[dict[str, Any]], Any],\n options: dict[str, Any] = {},\n **kw: Any,\n) -> Any:\n """\n Returns the result of an image function.\n\n :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band\n images, use the :py:meth:`~PIL.Image.Image.split` method or\n :py:func:`~PIL.Image.merge` function.\n\n :param expression: A function that receives a dictionary.\n :param options: Values to add to the function's dictionary. Deprecated.\n You can instead use one or more keyword arguments.\n :param **kw: Values to add to the function's dictionary.\n :return: The expression result. This is usually an image object, but can\n also be an integer, a floating point value, or a pixel tuple,\n depending on the expression.\n """\n\n if options:\n deprecate(\n "ImageMath.lambda_eval options",\n 12,\n "ImageMath.lambda_eval keyword arguments",\n )\n\n args: dict[str, Any] = ops.copy()\n args.update(options)\n args.update(kw)\n for k, v in args.items():\n if isinstance(v, Image.Image):\n args[k] = _Operand(v)\n\n out = expression(args)\n try:\n return out.im\n except AttributeError:\n return out\n\n\ndef unsafe_eval(\n expression: str,\n options: dict[str, Any] = {},\n **kw: Any,\n) -> Any:\n """\n Evaluates an image expression. This uses Python's ``eval()`` function to process\n the expression string, and carries the security risks of doing so. It is not\n recommended to process expressions without considering this.\n :py:meth:`~lambda_eval` is a more secure alternative.\n\n :py:mod:`~PIL.ImageMath` only supports single-layer images. To process multi-band\n images, use the :py:meth:`~PIL.Image.Image.split` method or\n :py:func:`~PIL.Image.merge` function.\n\n :param expression: A string containing a Python-style expression.\n :param options: Values to add to the evaluation context. Deprecated.\n You can instead use one or more keyword arguments.\n :param **kw: Values to add to the evaluation context.\n :return: The evaluated expression. This is usually an image object, but can\n also be an integer, a floating point value, or a pixel tuple,\n depending on the expression.\n """\n\n if options:\n deprecate(\n "ImageMath.unsafe_eval options",\n 12,\n "ImageMath.unsafe_eval keyword arguments",\n )\n\n # build execution namespace\n args: dict[str, Any] = ops.copy()\n for k in [*options, *kw]:\n if "__" in k or hasattr(builtins, k):\n msg = f"'{k}' not allowed"\n raise ValueError(msg)\n\n args.update(options)\n args.update(kw)\n for k, v in args.items():\n if isinstance(v, Image.Image):\n args[k] = _Operand(v)\n\n compiled_code = compile(expression, "<string>", "eval")\n\n def scan(code: CodeType) -> None:\n for const in code.co_consts:\n if type(const) is type(compiled_code):\n scan(const)\n\n for name in code.co_names:\n if name not in args and name != "abs":\n msg = f"'{name}' not allowed"\n raise ValueError(msg)\n\n scan(compiled_code)\n out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)\n try:\n return out.im\n except AttributeError:\n return out\n\n\ndef eval(\n expression: str,\n _dict: dict[str, Any] = {},\n **kw: Any,\n) -> Any:\n """\n Evaluates an image expression.\n\n Deprecated. Use lambda_eval() or unsafe_eval() instead.\n\n :param expression: A string containing a Python-style expression.\n :param _dict: Values to add to the evaluation context. You\n can either use a dictionary, or one or more keyword\n arguments.\n :return: The evaluated expression. This is usually an image object, but can\n also be an integer, a floating point value, or a pixel tuple,\n depending on the expression.\n\n .. deprecated:: 10.3.0\n """\n\n deprecate(\n "ImageMath.eval",\n 12,\n "ImageMath.lambda_eval or ImageMath.unsafe_eval",\n )\n return unsafe_eval(expression, _dict, **kw)\n | .venv\Lib\site-packages\PIL\ImageMath.py | ImageMath.py | Python | 12,287 | 0.95 | 0.233696 | 0.117241 | node-utils | 933 | 2024-08-17T03:25:18.653649 | Apache-2.0 | false | d2305627596c0a3567553d1353ef58e9 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# standard mode descriptors\n#\n# History:\n# 2006-03-20 fl Added\n#\n# Copyright (c) 2006 by Secret Labs AB.\n# Copyright (c) 2006 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport sys\nfrom functools import lru_cache\nfrom typing import NamedTuple\n\nfrom ._deprecate import deprecate\n\n\nclass ModeDescriptor(NamedTuple):\n """Wrapper for mode strings."""\n\n mode: str\n bands: tuple[str, ...]\n basemode: str\n basetype: str\n typestr: str\n\n def __str__(self) -> str:\n return self.mode\n\n\n@lru_cache\ndef getmode(mode: str) -> ModeDescriptor:\n """Gets a mode descriptor for the given mode."""\n endian = "<" if sys.byteorder == "little" else ">"\n\n modes = {\n # core modes\n # Bits need to be extended to bytes\n "1": ("L", "L", ("1",), "|b1"),\n "L": ("L", "L", ("L",), "|u1"),\n "I": ("L", "I", ("I",), f"{endian}i4"),\n "F": ("L", "F", ("F",), f"{endian}f4"),\n "P": ("P", "L", ("P",), "|u1"),\n "RGB": ("RGB", "L", ("R", "G", "B"), "|u1"),\n "RGBX": ("RGB", "L", ("R", "G", "B", "X"), "|u1"),\n "RGBA": ("RGB", "L", ("R", "G", "B", "A"), "|u1"),\n "CMYK": ("RGB", "L", ("C", "M", "Y", "K"), "|u1"),\n "YCbCr": ("RGB", "L", ("Y", "Cb", "Cr"), "|u1"),\n # UNDONE - unsigned |u1i1i1\n "LAB": ("RGB", "L", ("L", "A", "B"), "|u1"),\n "HSV": ("RGB", "L", ("H", "S", "V"), "|u1"),\n # extra experimental modes\n "RGBa": ("RGB", "L", ("R", "G", "B", "a"), "|u1"),\n "BGR;15": ("RGB", "L", ("B", "G", "R"), "|u1"),\n "BGR;16": ("RGB", "L", ("B", "G", "R"), "|u1"),\n "BGR;24": ("RGB", "L", ("B", "G", "R"), "|u1"),\n "LA": ("L", "L", ("L", "A"), "|u1"),\n "La": ("L", "L", ("L", "a"), "|u1"),\n "PA": ("RGB", "L", ("P", "A"), "|u1"),\n }\n if mode in modes:\n if mode in ("BGR;15", "BGR;16", "BGR;24"):\n deprecate(mode, 12)\n base_mode, base_type, bands, type_str = modes[mode]\n return ModeDescriptor(mode, bands, base_mode, base_type, type_str)\n\n mapping_modes = {\n # I;16 == I;16L, and I;32 == I;32L\n "I;16": "<u2",\n "I;16S": "<i2",\n "I;16L": "<u2",\n "I;16LS": "<i2",\n "I;16B": ">u2",\n "I;16BS": ">i2",\n "I;16N": f"{endian}u2",\n "I;16NS": f"{endian}i2",\n "I;32": "<u4",\n "I;32B": ">u4",\n "I;32L": "<u4",\n "I;32S": "<i4",\n "I;32BS": ">i4",\n "I;32LS": "<i4",\n }\n\n type_str = mapping_modes[mode]\n return ModeDescriptor(mode, ("I",), "L", "L", type_str)\n | .venv\Lib\site-packages\PIL\ImageMode.py | ImageMode.py | Python | 2,773 | 0.95 | 0.097826 | 0.234568 | react-lib | 306 | 2024-08-17T11:31:54.806015 | GPL-3.0 | false | dbc2ce47038724bcb952a33b58d25ab1 |
# A binary morphology add-on for the Python Imaging Library\n#\n# History:\n# 2014-06-04 Initial version.\n#\n# Copyright (c) 2014 Dov Grobgeld <dov.grobgeld@gmail.com>\nfrom __future__ import annotations\n\nimport re\n\nfrom . import Image, _imagingmorph\n\nLUT_SIZE = 1 << 9\n\n# fmt: off\nROTATION_MATRIX = [\n 6, 3, 0,\n 7, 4, 1,\n 8, 5, 2,\n]\nMIRROR_MATRIX = [\n 2, 1, 0,\n 5, 4, 3,\n 8, 7, 6,\n]\n# fmt: on\n\n\nclass LutBuilder:\n """A class for building a MorphLut from a descriptive language\n\n The input patterns is a list of a strings sequences like these::\n\n 4:(...\n .1.\n 111)->1\n\n (whitespaces including linebreaks are ignored). The option 4\n describes a series of symmetry operations (in this case a\n 4-rotation), the pattern is described by:\n\n - . or X - Ignore\n - 1 - Pixel is on\n - 0 - Pixel is off\n\n The result of the operation is described after "->" string.\n\n The default is to return the current pixel value, which is\n returned if no other match is found.\n\n Operations:\n\n - 4 - 4 way rotation\n - N - Negate\n - 1 - Dummy op for no other operation (an op must always be given)\n - M - Mirroring\n\n Example::\n\n lb = LutBuilder(patterns = ["4:(... .1. 111)->1"])\n lut = lb.build_lut()\n\n """\n\n def __init__(\n self, patterns: list[str] | None = None, op_name: str | None = None\n ) -> None:\n if patterns is not None:\n self.patterns = patterns\n else:\n self.patterns = []\n self.lut: bytearray | None = None\n if op_name is not None:\n known_patterns = {\n "corner": ["1:(... ... ...)->0", "4:(00. 01. ...)->1"],\n "dilation4": ["4:(... .0. .1.)->1"],\n "dilation8": ["4:(... .0. .1.)->1", "4:(... .0. ..1)->1"],\n "erosion4": ["4:(... .1. .0.)->0"],\n "erosion8": ["4:(... .1. .0.)->0", "4:(... .1. ..0)->0"],\n "edge": [\n "1:(... ... ...)->0",\n "4:(.0. .1. ...)->1",\n "4:(01. .1. ...)->1",\n ],\n }\n if op_name not in known_patterns:\n msg = f"Unknown pattern {op_name}!"\n raise Exception(msg)\n\n self.patterns = known_patterns[op_name]\n\n def add_patterns(self, patterns: list[str]) -> None:\n self.patterns += patterns\n\n def build_default_lut(self) -> None:\n symbols = [0, 1]\n m = 1 << 4 # pos of current pixel\n self.lut = bytearray(symbols[(i & m) > 0] for i in range(LUT_SIZE))\n\n def get_lut(self) -> bytearray | None:\n return self.lut\n\n def _string_permute(self, pattern: str, permutation: list[int]) -> str:\n """string_permute takes a pattern and a permutation and returns the\n string permuted according to the permutation list.\n """\n assert len(permutation) == 9\n return "".join(pattern[p] for p in permutation)\n\n def _pattern_permute(\n self, basic_pattern: str, options: str, basic_result: int\n ) -> list[tuple[str, int]]:\n """pattern_permute takes a basic pattern and its result and clones\n the pattern according to the modifications described in the $options\n parameter. It returns a list of all cloned patterns."""\n patterns = [(basic_pattern, basic_result)]\n\n # rotations\n if "4" in options:\n res = patterns[-1][1]\n for i in range(4):\n patterns.append(\n (self._string_permute(patterns[-1][0], ROTATION_MATRIX), res)\n )\n # mirror\n if "M" in options:\n n = len(patterns)\n for pattern, res in patterns[:n]:\n patterns.append((self._string_permute(pattern, MIRROR_MATRIX), res))\n\n # negate\n if "N" in options:\n n = len(patterns)\n for pattern, res in patterns[:n]:\n # Swap 0 and 1\n pattern = pattern.replace("0", "Z").replace("1", "0").replace("Z", "1")\n res = 1 - int(res)\n patterns.append((pattern, res))\n\n return patterns\n\n def build_lut(self) -> bytearray:\n """Compile all patterns into a morphology lut.\n\n TBD :Build based on (file) morphlut:modify_lut\n """\n self.build_default_lut()\n assert self.lut is not None\n patterns = []\n\n # Parse and create symmetries of the patterns strings\n for p in self.patterns:\n m = re.search(r"(\w*):?\s*\((.+?)\)\s*->\s*(\d)", p.replace("\n", ""))\n if not m:\n msg = 'Syntax error in pattern "' + p + '"'\n raise Exception(msg)\n options = m.group(1)\n pattern = m.group(2)\n result = int(m.group(3))\n\n # Get rid of spaces\n pattern = pattern.replace(" ", "").replace("\n", "")\n\n patterns += self._pattern_permute(pattern, options, result)\n\n # compile the patterns into regular expressions for speed\n compiled_patterns = []\n for pattern in patterns:\n p = pattern[0].replace(".", "X").replace("X", "[01]")\n compiled_patterns.append((re.compile(p), pattern[1]))\n\n # Step through table and find patterns that match.\n # Note that all the patterns are searched. The last one\n # caught overrides\n for i in range(LUT_SIZE):\n # Build the bit pattern\n bitpattern = bin(i)[2:]\n bitpattern = ("0" * (9 - len(bitpattern)) + bitpattern)[::-1]\n\n for pattern, r in compiled_patterns:\n if pattern.match(bitpattern):\n self.lut[i] = [0, 1][r]\n\n return self.lut\n\n\nclass MorphOp:\n """A class for binary morphological operators"""\n\n def __init__(\n self,\n lut: bytearray | None = None,\n op_name: str | None = None,\n patterns: list[str] | None = None,\n ) -> None:\n """Create a binary morphological operator"""\n self.lut = lut\n if op_name is not None:\n self.lut = LutBuilder(op_name=op_name).build_lut()\n elif patterns is not None:\n self.lut = LutBuilder(patterns=patterns).build_lut()\n\n def apply(self, image: Image.Image) -> tuple[int, Image.Image]:\n """Run a single morphological operation on an image\n\n Returns a tuple of the number of changed pixels and the\n morphed image"""\n if self.lut is None:\n msg = "No operator loaded"\n raise Exception(msg)\n\n if image.mode != "L":\n msg = "Image mode must be L"\n raise ValueError(msg)\n outimage = Image.new(image.mode, image.size, None)\n count = _imagingmorph.apply(bytes(self.lut), image.getim(), outimage.getim())\n return count, outimage\n\n def match(self, image: Image.Image) -> list[tuple[int, int]]:\n """Get a list of coordinates matching the morphological operation on\n an image.\n\n Returns a list of tuples of (x,y) coordinates\n of all matching pixels. See :ref:`coordinate-system`."""\n if self.lut is None:\n msg = "No operator loaded"\n raise Exception(msg)\n\n if image.mode != "L":\n msg = "Image mode must be L"\n raise ValueError(msg)\n return _imagingmorph.match(bytes(self.lut), image.getim())\n\n def get_on_pixels(self, image: Image.Image) -> list[tuple[int, int]]:\n """Get a list of all turned on pixels in a binary image\n\n Returns a list of tuples of (x,y) coordinates\n of all matching pixels. See :ref:`coordinate-system`."""\n\n if image.mode != "L":\n msg = "Image mode must be L"\n raise ValueError(msg)\n return _imagingmorph.get_on_pixels(image.getim())\n\n def load_lut(self, filename: str) -> None:\n """Load an operator from an mrl file"""\n with open(filename, "rb") as f:\n self.lut = bytearray(f.read())\n\n if len(self.lut) != LUT_SIZE:\n self.lut = None\n msg = "Wrong size operator file!"\n raise Exception(msg)\n\n def save_lut(self, filename: str) -> None:\n """Save an operator to an mrl file"""\n if self.lut is None:\n msg = "No operator loaded"\n raise Exception(msg)\n with open(filename, "wb") as f:\n f.write(self.lut)\n\n def set_lut(self, lut: bytearray | None) -> None:\n """Set the lut from an external source"""\n self.lut = lut\n | .venv\Lib\site-packages\PIL\ImageMorph.py | ImageMorph.py | Python | 8,828 | 0.95 | 0.184906 | 0.089202 | node-utils | 622 | 2024-05-17T21:44:01.344944 | GPL-3.0 | false | 0b3579d0e1e0615d7349a808b0576936 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# standard image operations\n#\n# History:\n# 2001-10-20 fl Created\n# 2001-10-23 fl Added autocontrast operator\n# 2001-12-18 fl Added Kevin's fit operator\n# 2004-03-14 fl Fixed potential division by zero in equalize\n# 2005-05-05 fl Fixed equalize for low number of values\n#\n# Copyright (c) 2001-2004 by Secret Labs AB\n# Copyright (c) 2001-2004 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport functools\nimport operator\nimport re\nfrom collections.abc import Sequence\nfrom typing import Literal, Protocol, cast, overload\n\nfrom . import ExifTags, Image, ImagePalette\n\n#\n# helpers\n\n\ndef _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:\n if isinstance(border, tuple):\n if len(border) == 2:\n left, top = right, bottom = border\n elif len(border) == 4:\n left, top, right, bottom = border\n else:\n left = top = right = bottom = border\n return left, top, right, bottom\n\n\ndef _color(color: str | int | tuple[int, ...], mode: str) -> int | tuple[int, ...]:\n if isinstance(color, str):\n from . import ImageColor\n\n color = ImageColor.getcolor(color, mode)\n return color\n\n\ndef _lut(image: Image.Image, lut: list[int]) -> Image.Image:\n if image.mode == "P":\n # FIXME: apply to lookup table, not image data\n msg = "mode P support coming soon"\n raise NotImplementedError(msg)\n elif image.mode in ("L", "RGB"):\n if image.mode == "RGB" and len(lut) == 256:\n lut = lut + lut + lut\n return image.point(lut)\n else:\n msg = f"not supported for mode {image.mode}"\n raise OSError(msg)\n\n\n#\n# actions\n\n\ndef autocontrast(\n image: Image.Image,\n cutoff: float | tuple[float, float] = 0,\n ignore: int | Sequence[int] | None = None,\n mask: Image.Image | None = None,\n preserve_tone: bool = False,\n) -> Image.Image:\n """\n Maximize (normalize) image contrast. This function calculates a\n histogram of the input image (or mask region), removes ``cutoff`` percent of the\n lightest and darkest pixels from the histogram, and remaps the image\n so that the darkest pixel becomes black (0), and the lightest\n becomes white (255).\n\n :param image: The image to process.\n :param cutoff: The percent to cut off from the histogram on the low and\n high ends. Either a tuple of (low, high), or a single\n number for both.\n :param ignore: The background pixel value (use None for no background).\n :param mask: Histogram used in contrast operation is computed using pixels\n within the mask. If no mask is given the entire image is used\n for histogram computation.\n :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.\n\n .. versionadded:: 8.2.0\n\n :return: An image.\n """\n if preserve_tone:\n histogram = image.convert("L").histogram(mask)\n else:\n histogram = image.histogram(mask)\n\n lut = []\n for layer in range(0, len(histogram), 256):\n h = histogram[layer : layer + 256]\n if ignore is not None:\n # get rid of outliers\n if isinstance(ignore, int):\n h[ignore] = 0\n else:\n for ix in ignore:\n h[ix] = 0\n if cutoff:\n # cut off pixels from both ends of the histogram\n if not isinstance(cutoff, tuple):\n cutoff = (cutoff, cutoff)\n # get number of pixels\n n = 0\n for ix in range(256):\n n = n + h[ix]\n # remove cutoff% pixels from the low end\n cut = int(n * cutoff[0] // 100)\n for lo in range(256):\n if cut > h[lo]:\n cut = cut - h[lo]\n h[lo] = 0\n else:\n h[lo] -= cut\n cut = 0\n if cut <= 0:\n break\n # remove cutoff% samples from the high end\n cut = int(n * cutoff[1] // 100)\n for hi in range(255, -1, -1):\n if cut > h[hi]:\n cut = cut - h[hi]\n h[hi] = 0\n else:\n h[hi] -= cut\n cut = 0\n if cut <= 0:\n break\n # find lowest/highest samples after preprocessing\n for lo in range(256):\n if h[lo]:\n break\n for hi in range(255, -1, -1):\n if h[hi]:\n break\n if hi <= lo:\n # don't bother\n lut.extend(list(range(256)))\n else:\n scale = 255.0 / (hi - lo)\n offset = -lo * scale\n for ix in range(256):\n ix = int(ix * scale + offset)\n if ix < 0:\n ix = 0\n elif ix > 255:\n ix = 255\n lut.append(ix)\n return _lut(image, lut)\n\n\ndef colorize(\n image: Image.Image,\n black: str | tuple[int, ...],\n white: str | tuple[int, ...],\n mid: str | int | tuple[int, ...] | None = None,\n blackpoint: int = 0,\n whitepoint: int = 255,\n midpoint: int = 127,\n) -> Image.Image:\n """\n Colorize grayscale image.\n This function calculates a color wedge which maps all black pixels in\n the source image to the first color and all white pixels to the\n second color. If ``mid`` is specified, it uses three-color mapping.\n The ``black`` and ``white`` arguments should be RGB tuples or color names;\n optionally you can use three-color mapping by also specifying ``mid``.\n Mapping positions for any of the colors can be specified\n (e.g. ``blackpoint``), where these parameters are the integer\n value corresponding to where the corresponding color should be mapped.\n These parameters must have logical order, such that\n ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).\n\n :param image: The image to colorize.\n :param black: The color to use for black input pixels.\n :param white: The color to use for white input pixels.\n :param mid: The color to use for midtone input pixels.\n :param blackpoint: an int value [0, 255] for the black mapping.\n :param whitepoint: an int value [0, 255] for the white mapping.\n :param midpoint: an int value [0, 255] for the midtone mapping.\n :return: An image.\n """\n\n # Initial asserts\n assert image.mode == "L"\n if mid is None:\n assert 0 <= blackpoint <= whitepoint <= 255\n else:\n assert 0 <= blackpoint <= midpoint <= whitepoint <= 255\n\n # Define colors from arguments\n rgb_black = cast(Sequence[int], _color(black, "RGB"))\n rgb_white = cast(Sequence[int], _color(white, "RGB"))\n rgb_mid = cast(Sequence[int], _color(mid, "RGB")) if mid is not None else None\n\n # Empty lists for the mapping\n red = []\n green = []\n blue = []\n\n # Create the low-end values\n for i in range(blackpoint):\n red.append(rgb_black[0])\n green.append(rgb_black[1])\n blue.append(rgb_black[2])\n\n # Create the mapping (2-color)\n if rgb_mid is None:\n range_map = range(whitepoint - blackpoint)\n\n for i in range_map:\n red.append(\n rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)\n )\n green.append(\n rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)\n )\n blue.append(\n rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)\n )\n\n # Create the mapping (3-color)\n else:\n range_map1 = range(midpoint - blackpoint)\n range_map2 = range(whitepoint - midpoint)\n\n for i in range_map1:\n red.append(\n rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)\n )\n green.append(\n rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)\n )\n blue.append(\n rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)\n )\n for i in range_map2:\n red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))\n green.append(\n rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)\n )\n blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))\n\n # Create the high-end values\n for i in range(256 - whitepoint):\n red.append(rgb_white[0])\n green.append(rgb_white[1])\n blue.append(rgb_white[2])\n\n # Return converted image\n image = image.convert("RGB")\n return _lut(image, red + green + blue)\n\n\ndef contain(\n image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC\n) -> Image.Image:\n """\n Returns a resized version of the image, set to the maximum width and height\n within the requested size, while maintaining the original aspect ratio.\n\n :param image: The image to resize.\n :param size: The requested output size in pixels, given as a\n (width, height) tuple.\n :param method: Resampling method to use. Default is\n :py:attr:`~PIL.Image.Resampling.BICUBIC`.\n See :ref:`concept-filters`.\n :return: An image.\n """\n\n im_ratio = image.width / image.height\n dest_ratio = size[0] / size[1]\n\n if im_ratio != dest_ratio:\n if im_ratio > dest_ratio:\n new_height = round(image.height / image.width * size[0])\n if new_height != size[1]:\n size = (size[0], new_height)\n else:\n new_width = round(image.width / image.height * size[1])\n if new_width != size[0]:\n size = (new_width, size[1])\n return image.resize(size, resample=method)\n\n\ndef cover(\n image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC\n) -> Image.Image:\n """\n Returns a resized version of the image, so that the requested size is\n covered, while maintaining the original aspect ratio.\n\n :param image: The image to resize.\n :param size: The requested output size in pixels, given as a\n (width, height) tuple.\n :param method: Resampling method to use. Default is\n :py:attr:`~PIL.Image.Resampling.BICUBIC`.\n See :ref:`concept-filters`.\n :return: An image.\n """\n\n im_ratio = image.width / image.height\n dest_ratio = size[0] / size[1]\n\n if im_ratio != dest_ratio:\n if im_ratio < dest_ratio:\n new_height = round(image.height / image.width * size[0])\n if new_height != size[1]:\n size = (size[0], new_height)\n else:\n new_width = round(image.width / image.height * size[1])\n if new_width != size[0]:\n size = (new_width, size[1])\n return image.resize(size, resample=method)\n\n\ndef pad(\n image: Image.Image,\n size: tuple[int, int],\n method: int = Image.Resampling.BICUBIC,\n color: str | int | tuple[int, ...] | None = None,\n centering: tuple[float, float] = (0.5, 0.5),\n) -> Image.Image:\n """\n Returns a resized and padded version of the image, expanded to fill the\n requested aspect ratio and size.\n\n :param image: The image to resize and crop.\n :param size: The requested output size in pixels, given as a\n (width, height) tuple.\n :param method: Resampling method to use. Default is\n :py:attr:`~PIL.Image.Resampling.BICUBIC`.\n See :ref:`concept-filters`.\n :param color: The background color of the padded image.\n :param centering: Control the position of the original image within the\n padded version.\n\n (0.5, 0.5) will keep the image centered\n (0, 0) will keep the image aligned to the top left\n (1, 1) will keep the image aligned to the bottom\n right\n :return: An image.\n """\n\n resized = contain(image, size, method)\n if resized.size == size:\n out = resized\n else:\n out = Image.new(image.mode, size, color)\n if resized.palette:\n palette = resized.getpalette()\n if palette is not None:\n out.putpalette(palette)\n if resized.width != size[0]:\n x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))\n out.paste(resized, (x, 0))\n else:\n y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))\n out.paste(resized, (0, y))\n return out\n\n\ndef crop(image: Image.Image, border: int = 0) -> Image.Image:\n """\n Remove border from image. The same amount of pixels are removed\n from all four sides. This function works on all image modes.\n\n .. seealso:: :py:meth:`~PIL.Image.Image.crop`\n\n :param image: The image to crop.\n :param border: The number of pixels to remove.\n :return: An image.\n """\n left, top, right, bottom = _border(border)\n return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))\n\n\ndef scale(\n image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC\n) -> Image.Image:\n """\n Returns a rescaled image by a specific factor given in parameter.\n A factor greater than 1 expands the image, between 0 and 1 contracts the\n image.\n\n :param image: The image to rescale.\n :param factor: The expansion factor, as a float.\n :param resample: Resampling method to use. Default is\n :py:attr:`~PIL.Image.Resampling.BICUBIC`.\n See :ref:`concept-filters`.\n :returns: An :py:class:`~PIL.Image.Image` object.\n """\n if factor == 1:\n return image.copy()\n elif factor <= 0:\n msg = "the factor must be greater than 0"\n raise ValueError(msg)\n else:\n size = (round(factor * image.width), round(factor * image.height))\n return image.resize(size, resample)\n\n\nclass SupportsGetMesh(Protocol):\n """\n An object that supports the ``getmesh`` method, taking an image as an\n argument, and returning a list of tuples. Each tuple contains two tuples,\n the source box as a tuple of 4 integers, and a tuple of 8 integers for the\n final quadrilateral, in order of top left, bottom left, bottom right, top\n right.\n """\n\n def getmesh(\n self, image: Image.Image\n ) -> list[\n tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]\n ]: ...\n\n\ndef deform(\n image: Image.Image,\n deformer: SupportsGetMesh,\n resample: int = Image.Resampling.BILINEAR,\n) -> Image.Image:\n """\n Deform the image.\n\n :param image: The image to deform.\n :param deformer: A deformer object. Any object that implements a\n ``getmesh`` method can be used.\n :param resample: An optional resampling filter. Same values possible as\n in the PIL.Image.transform function.\n :return: An image.\n """\n return image.transform(\n image.size, Image.Transform.MESH, deformer.getmesh(image), resample\n )\n\n\ndef equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:\n """\n Equalize the image histogram. This function applies a non-linear\n mapping to the input image, in order to create a uniform\n distribution of grayscale values in the output image.\n\n :param image: The image to equalize.\n :param mask: An optional mask. If given, only the pixels selected by\n the mask are included in the analysis.\n :return: An image.\n """\n if image.mode == "P":\n image = image.convert("RGB")\n h = image.histogram(mask)\n lut = []\n for b in range(0, len(h), 256):\n histo = [_f for _f in h[b : b + 256] if _f]\n if len(histo) <= 1:\n lut.extend(list(range(256)))\n else:\n step = (functools.reduce(operator.add, histo) - histo[-1]) // 255\n if not step:\n lut.extend(list(range(256)))\n else:\n n = step // 2\n for i in range(256):\n lut.append(n // step)\n n = n + h[i + b]\n return _lut(image, lut)\n\n\ndef expand(\n image: Image.Image,\n border: int | tuple[int, ...] = 0,\n fill: str | int | tuple[int, ...] = 0,\n) -> Image.Image:\n """\n Add border to the image\n\n :param image: The image to expand.\n :param border: Border width, in pixels.\n :param fill: Pixel fill value (a color value). Default is 0 (black).\n :return: An image.\n """\n left, top, right, bottom = _border(border)\n width = left + image.size[0] + right\n height = top + image.size[1] + bottom\n color = _color(fill, image.mode)\n if image.palette:\n palette = ImagePalette.ImagePalette(palette=image.getpalette())\n if isinstance(color, tuple) and (len(color) == 3 or len(color) == 4):\n color = palette.getcolor(color)\n else:\n palette = None\n out = Image.new(image.mode, (width, height), color)\n if palette:\n out.putpalette(palette.palette)\n out.paste(image, (left, top))\n return out\n\n\ndef fit(\n image: Image.Image,\n size: tuple[int, int],\n method: int = Image.Resampling.BICUBIC,\n bleed: float = 0.0,\n centering: tuple[float, float] = (0.5, 0.5),\n) -> Image.Image:\n """\n Returns a resized and cropped version of the image, cropped to the\n requested aspect ratio and size.\n\n This function was contributed by Kevin Cazabon.\n\n :param image: The image to resize and crop.\n :param size: The requested output size in pixels, given as a\n (width, height) tuple.\n :param method: Resampling method to use. Default is\n :py:attr:`~PIL.Image.Resampling.BICUBIC`.\n See :ref:`concept-filters`.\n :param bleed: Remove a border around the outside of the image from all\n four edges. The value is a decimal percentage (use 0.01 for\n one percent). The default value is 0 (no border).\n Cannot be greater than or equal to 0.5.\n :param centering: Control the cropping position. Use (0.5, 0.5) for\n center cropping (e.g. if cropping the width, take 50% off\n of the left side, and therefore 50% off the right side).\n (0.0, 0.0) will crop from the top left corner (i.e. if\n cropping the width, take all of the crop off of the right\n side, and if cropping the height, take all of it off the\n bottom). (1.0, 0.0) will crop from the bottom left\n corner, etc. (i.e. if cropping the width, take all of the\n crop off the left side, and if cropping the height take\n none from the top, and therefore all off the bottom).\n :return: An image.\n """\n\n # by Kevin Cazabon, Feb 17/2000\n # kevin@cazabon.com\n # https://www.cazabon.com\n\n centering_x, centering_y = centering\n\n if not 0.0 <= centering_x <= 1.0:\n centering_x = 0.5\n if not 0.0 <= centering_y <= 1.0:\n centering_y = 0.5\n\n if not 0.0 <= bleed < 0.5:\n bleed = 0.0\n\n # calculate the area to use for resizing and cropping, subtracting\n # the 'bleed' around the edges\n\n # number of pixels to trim off on Top and Bottom, Left and Right\n bleed_pixels = (bleed * image.size[0], bleed * image.size[1])\n\n live_size = (\n image.size[0] - bleed_pixels[0] * 2,\n image.size[1] - bleed_pixels[1] * 2,\n )\n\n # calculate the aspect ratio of the live_size\n live_size_ratio = live_size[0] / live_size[1]\n\n # calculate the aspect ratio of the output image\n output_ratio = size[0] / size[1]\n\n # figure out if the sides or top/bottom will be cropped off\n if live_size_ratio == output_ratio:\n # live_size is already the needed ratio\n crop_width = live_size[0]\n crop_height = live_size[1]\n elif live_size_ratio >= output_ratio:\n # live_size is wider than what's needed, crop the sides\n crop_width = output_ratio * live_size[1]\n crop_height = live_size[1]\n else:\n # live_size is taller than what's needed, crop the top and bottom\n crop_width = live_size[0]\n crop_height = live_size[0] / output_ratio\n\n # make the crop\n crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x\n crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y\n\n crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)\n\n # resize the image and return it\n return image.resize(size, method, box=crop)\n\n\ndef flip(image: Image.Image) -> Image.Image:\n """\n Flip the image vertically (top to bottom).\n\n :param image: The image to flip.\n :return: An image.\n """\n return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)\n\n\ndef grayscale(image: Image.Image) -> Image.Image:\n """\n Convert the image to grayscale.\n\n :param image: The image to convert.\n :return: An image.\n """\n return image.convert("L")\n\n\ndef invert(image: Image.Image) -> Image.Image:\n """\n Invert (negate) the image.\n\n :param image: The image to invert.\n :return: An image.\n """\n lut = list(range(255, -1, -1))\n return image.point(lut) if image.mode == "1" else _lut(image, lut)\n\n\ndef mirror(image: Image.Image) -> Image.Image:\n """\n Flip image horizontally (left to right).\n\n :param image: The image to mirror.\n :return: An image.\n """\n return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n\n\ndef posterize(image: Image.Image, bits: int) -> Image.Image:\n """\n Reduce the number of bits for each color channel.\n\n :param image: The image to posterize.\n :param bits: The number of bits to keep for each channel (1-8).\n :return: An image.\n """\n mask = ~(2 ** (8 - bits) - 1)\n lut = [i & mask for i in range(256)]\n return _lut(image, lut)\n\n\ndef solarize(image: Image.Image, threshold: int = 128) -> Image.Image:\n """\n Invert all pixel values above a threshold.\n\n :param image: The image to solarize.\n :param threshold: All pixels above this grayscale level are inverted.\n :return: An image.\n """\n lut = []\n for i in range(256):\n if i < threshold:\n lut.append(i)\n else:\n lut.append(255 - i)\n return _lut(image, lut)\n\n\n@overload\ndef exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...\n\n\n@overload\ndef exif_transpose(\n image: Image.Image, *, in_place: Literal[False] = False\n) -> Image.Image: ...\n\n\ndef exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:\n """\n If an image has an EXIF Orientation tag, other than 1, transpose the image\n accordingly, and remove the orientation data.\n\n :param image: The image to transpose.\n :param in_place: Boolean. Keyword-only argument.\n If ``True``, the original image is modified in-place, and ``None`` is returned.\n If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned\n with the transposition applied. If there is no transposition, a copy of the\n image will be returned.\n """\n image.load()\n image_exif = image.getexif()\n orientation = image_exif.get(ExifTags.Base.Orientation, 1)\n method = {\n 2: Image.Transpose.FLIP_LEFT_RIGHT,\n 3: Image.Transpose.ROTATE_180,\n 4: Image.Transpose.FLIP_TOP_BOTTOM,\n 5: Image.Transpose.TRANSPOSE,\n 6: Image.Transpose.ROTATE_270,\n 7: Image.Transpose.TRANSVERSE,\n 8: Image.Transpose.ROTATE_90,\n }.get(orientation)\n if method is not None:\n if in_place:\n image.im = image.im.transpose(method)\n image._size = image.im.size\n else:\n transposed_image = image.transpose(method)\n exif_image = image if in_place else transposed_image\n\n exif = exif_image.getexif()\n if ExifTags.Base.Orientation in exif:\n del exif[ExifTags.Base.Orientation]\n if "exif" in exif_image.info:\n exif_image.info["exif"] = exif.tobytes()\n elif "Raw profile type exif" in exif_image.info:\n exif_image.info["Raw profile type exif"] = exif.tobytes().hex()\n for key in ("XML:com.adobe.xmp", "xmp"):\n if key in exif_image.info:\n for pattern in (\n r'tiff:Orientation="([0-9])"',\n r"<tiff:Orientation>([0-9])</tiff:Orientation>",\n ):\n value = exif_image.info[key]\n if isinstance(value, str):\n value = re.sub(pattern, "", value)\n elif isinstance(value, tuple):\n value = tuple(\n re.sub(pattern.encode(), b"", v) for v in value\n )\n else:\n value = re.sub(pattern.encode(), b"", value)\n exif_image.info[key] = value\n if not in_place:\n return transposed_image\n elif not in_place:\n return image.copy()\n return None\n | .venv\Lib\site-packages\PIL\ImageOps.py | ImageOps.py | Python | 26,270 | 0.95 | 0.185235 | 0.081633 | vue-tools | 461 | 2024-07-05T16:19:31.143943 | BSD-3-Clause | false | cefd14153680139b7dd7716baf2cf431 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# image palette object\n#\n# History:\n# 1996-03-11 fl Rewritten.\n# 1997-01-03 fl Up and running.\n# 1997-08-23 fl Added load hack\n# 2001-04-16 fl Fixed randint shadow bug in random()\n#\n# Copyright (c) 1997-2001 by Secret Labs AB\n# Copyright (c) 1996-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport array\nfrom collections.abc import Sequence\nfrom typing import IO\n\nfrom . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from . import Image\n\n\nclass ImagePalette:\n """\n Color palette for palette mapped images\n\n :param mode: The mode to use for the palette. See:\n :ref:`concept-modes`. Defaults to "RGB"\n :param palette: An optional palette. If given, it must be a bytearray,\n an array or a list of ints between 0-255. The list must consist of\n all channels for one color followed by the next color (e.g. RGBRGBRGB).\n Defaults to an empty palette.\n """\n\n def __init__(\n self,\n mode: str = "RGB",\n palette: Sequence[int] | bytes | bytearray | None = None,\n ) -> None:\n self.mode = mode\n self.rawmode: str | None = None # if set, palette contains raw data\n self.palette = palette or bytearray()\n self.dirty: int | None = None\n\n @property\n def palette(self) -> Sequence[int] | bytes | bytearray:\n return self._palette\n\n @palette.setter\n def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:\n self._colors: dict[tuple[int, ...], int] | None = None\n self._palette = palette\n\n @property\n def colors(self) -> dict[tuple[int, ...], int]:\n if self._colors is None:\n mode_len = len(self.mode)\n self._colors = {}\n for i in range(0, len(self.palette), mode_len):\n color = tuple(self.palette[i : i + mode_len])\n if color in self._colors:\n continue\n self._colors[color] = i // mode_len\n return self._colors\n\n @colors.setter\n def colors(self, colors: dict[tuple[int, ...], int]) -> None:\n self._colors = colors\n\n def copy(self) -> ImagePalette:\n new = ImagePalette()\n\n new.mode = self.mode\n new.rawmode = self.rawmode\n if self.palette is not None:\n new.palette = self.palette[:]\n new.dirty = self.dirty\n\n return new\n\n def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:\n """\n Get palette contents in format suitable for the low-level\n ``im.putpalette`` primitive.\n\n .. warning:: This method is experimental.\n """\n if self.rawmode:\n return self.rawmode, self.palette\n return self.mode, self.tobytes()\n\n def tobytes(self) -> bytes:\n """Convert palette to bytes.\n\n .. warning:: This method is experimental.\n """\n if self.rawmode:\n msg = "palette contains raw palette data"\n raise ValueError(msg)\n if isinstance(self.palette, bytes):\n return self.palette\n arr = array.array("B", self.palette)\n return arr.tobytes()\n\n # Declare tostring as an alias for tobytes\n tostring = tobytes\n\n def _new_color_index(\n self, image: Image.Image | None = None, e: Exception | None = None\n ) -> int:\n if not isinstance(self.palette, bytearray):\n self._palette = bytearray(self.palette)\n index = len(self.palette) // 3\n special_colors: tuple[int | tuple[int, ...] | None, ...] = ()\n if image:\n special_colors = (\n image.info.get("background"),\n image.info.get("transparency"),\n )\n while index in special_colors:\n index += 1\n if index >= 256:\n if image:\n # Search for an unused index\n for i, count in reversed(list(enumerate(image.histogram()))):\n if count == 0 and i not in special_colors:\n index = i\n break\n if index >= 256:\n msg = "cannot allocate more than 256 colors"\n raise ValueError(msg) from e\n return index\n\n def getcolor(\n self,\n color: tuple[int, ...],\n image: Image.Image | None = None,\n ) -> int:\n """Given an rgb tuple, allocate palette entry.\n\n .. warning:: This method is experimental.\n """\n if self.rawmode:\n msg = "palette contains raw palette data"\n raise ValueError(msg)\n if isinstance(color, tuple):\n if self.mode == "RGB":\n if len(color) == 4:\n if color[3] != 255:\n msg = "cannot add non-opaque RGBA color to RGB palette"\n raise ValueError(msg)\n color = color[:3]\n elif self.mode == "RGBA":\n if len(color) == 3:\n color += (255,)\n try:\n return self.colors[color]\n except KeyError as e:\n # allocate new color slot\n index = self._new_color_index(image, e)\n assert isinstance(self._palette, bytearray)\n self.colors[color] = index\n if index * 3 < len(self.palette):\n self._palette = (\n self._palette[: index * 3]\n + bytes(color)\n + self._palette[index * 3 + 3 :]\n )\n else:\n self._palette += bytes(color)\n self.dirty = 1\n return index\n else:\n msg = f"unknown color specifier: {repr(color)}" # type: ignore[unreachable]\n raise ValueError(msg)\n\n def save(self, fp: str | IO[str]) -> None:\n """Save palette to text file.\n\n .. warning:: This method is experimental.\n """\n if self.rawmode:\n msg = "palette contains raw palette data"\n raise ValueError(msg)\n if isinstance(fp, str):\n fp = open(fp, "w")\n fp.write("# Palette\n")\n fp.write(f"# Mode: {self.mode}\n")\n for i in range(256):\n fp.write(f"{i}")\n for j in range(i * len(self.mode), (i + 1) * len(self.mode)):\n try:\n fp.write(f" {self.palette[j]}")\n except IndexError:\n fp.write(" 0")\n fp.write("\n")\n fp.close()\n\n\n# --------------------------------------------------------------------\n# Internal\n\n\ndef raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:\n palette = ImagePalette()\n palette.rawmode = rawmode\n palette.palette = data\n palette.dirty = 1\n return palette\n\n\n# --------------------------------------------------------------------\n# Factories\n\n\ndef make_linear_lut(black: int, white: float) -> list[int]:\n if black == 0:\n return [int(white * i // 255) for i in range(256)]\n\n msg = "unavailable when black is non-zero"\n raise NotImplementedError(msg) # FIXME\n\n\ndef make_gamma_lut(exp: float) -> list[int]:\n return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]\n\n\ndef negative(mode: str = "RGB") -> ImagePalette:\n palette = list(range(256 * len(mode)))\n palette.reverse()\n return ImagePalette(mode, [i // len(mode) for i in palette])\n\n\ndef random(mode: str = "RGB") -> ImagePalette:\n from random import randint\n\n palette = [randint(0, 255) for _ in range(256 * len(mode))]\n return ImagePalette(mode, palette)\n\n\ndef sepia(white: str = "#fff0c0") -> ImagePalette:\n bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]\n return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])\n\n\ndef wedge(mode: str = "RGB") -> ImagePalette:\n palette = list(range(256 * len(mode)))\n return ImagePalette(mode, [i // len(mode) for i in palette])\n\n\ndef load(filename: str) -> tuple[bytes, str]:\n # FIXME: supports GIMP gradients only\n\n with open(filename, "rb") as fp:\n paletteHandlers: list[\n type[\n GimpPaletteFile.GimpPaletteFile\n | GimpGradientFile.GimpGradientFile\n | PaletteFile.PaletteFile\n ]\n ] = [\n GimpPaletteFile.GimpPaletteFile,\n GimpGradientFile.GimpGradientFile,\n PaletteFile.PaletteFile,\n ]\n for paletteHandler in paletteHandlers:\n try:\n fp.seek(0)\n lut = paletteHandler(fp).getpalette()\n if lut:\n break\n except (SyntaxError, ValueError):\n pass\n else:\n msg = "cannot load palette"\n raise OSError(msg)\n\n return lut # data, rawmode\n | .venv\Lib\site-packages\PIL\ImagePalette.py | ImagePalette.py | Python | 9,295 | 0.95 | 0.237762 | 0.105042 | python-kit | 416 | 2023-10-18T10:01:29.363773 | BSD-3-Clause | false | 5111fd275d0806ed6667242df48d2ae1 |
#\n# The Python Imaging Library\n# $Id$\n#\n# path interface\n#\n# History:\n# 1996-11-04 fl Created\n# 2002-04-14 fl Added documentation stub class\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image\n\nPath = Image.core.path\n | .venv\Lib\site-packages\PIL\ImagePath.py | ImagePath.py | Python | 391 | 0.95 | 0.1 | 0.833333 | vue-tools | 372 | 2024-07-14T10:53:23.134870 | Apache-2.0 | false | 00d31ab51ea8b9c5391bd262d0aacde4 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# a simple Qt image interface.\n#\n# history:\n# 2006-06-03 fl: created\n# 2006-06-04 fl: inherit from QImage instead of wrapping it\n# 2006-06-05 fl: removed toimage helper; move string support to ImageQt\n# 2013-11-13 fl: add support for Qt5 (aurelien.ballier@cyclonit.com)\n#\n# Copyright (c) 2006 by Secret Labs AB\n# Copyright (c) 2006 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport sys\nfrom io import BytesIO\nfrom typing import Any, Callable, Union\n\nfrom . import Image\nfrom ._util import is_path\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n import PyQt6\n import PySide6\n\n from . import ImageFile\n\n QBuffer: type\n QByteArray = Union[PyQt6.QtCore.QByteArray, PySide6.QtCore.QByteArray]\n QIODevice = Union[PyQt6.QtCore.QIODevice, PySide6.QtCore.QIODevice]\n QImage = Union[PyQt6.QtGui.QImage, PySide6.QtGui.QImage]\n QPixmap = Union[PyQt6.QtGui.QPixmap, PySide6.QtGui.QPixmap]\n\nqt_version: str | None\nqt_versions = [\n ["6", "PyQt6"],\n ["side6", "PySide6"],\n]\n\n# If a version has already been imported, attempt it first\nqt_versions.sort(key=lambda version: version[1] in sys.modules, reverse=True)\nfor version, qt_module in qt_versions:\n try:\n qRgba: Callable[[int, int, int, int], int]\n if qt_module == "PyQt6":\n from PyQt6.QtCore import QBuffer, QIODevice\n from PyQt6.QtGui import QImage, QPixmap, qRgba\n elif qt_module == "PySide6":\n from PySide6.QtCore import QBuffer, QIODevice\n from PySide6.QtGui import QImage, QPixmap, qRgba\n except (ImportError, RuntimeError):\n continue\n qt_is_installed = True\n qt_version = version\n break\nelse:\n qt_is_installed = False\n qt_version = None\n\n\ndef rgb(r: int, g: int, b: int, a: int = 255) -> int:\n """(Internal) Turns an RGB color into a Qt compatible color integer."""\n # use qRgb to pack the colors, and then turn the resulting long\n # into a negative integer with the same bitpattern.\n return qRgba(r, g, b, a) & 0xFFFFFFFF\n\n\ndef fromqimage(im: QImage | QPixmap) -> ImageFile.ImageFile:\n """\n :param im: QImage or PIL ImageQt object\n """\n buffer = QBuffer()\n qt_openmode: object\n if qt_version == "6":\n try:\n qt_openmode = getattr(QIODevice, "OpenModeFlag")\n except AttributeError:\n qt_openmode = getattr(QIODevice, "OpenMode")\n else:\n qt_openmode = QIODevice\n buffer.open(getattr(qt_openmode, "ReadWrite"))\n # preserve alpha channel with png\n # otherwise ppm is more friendly with Image.open\n if im.hasAlphaChannel():\n im.save(buffer, "png")\n else:\n im.save(buffer, "ppm")\n\n b = BytesIO()\n b.write(buffer.data())\n buffer.close()\n b.seek(0)\n\n return Image.open(b)\n\n\ndef fromqpixmap(im: QPixmap) -> ImageFile.ImageFile:\n return fromqimage(im)\n\n\ndef align8to32(bytes: bytes, width: int, mode: str) -> bytes:\n """\n converts each scanline of data from 8 bit to 32 bit aligned\n """\n\n bits_per_pixel = {"1": 1, "L": 8, "P": 8, "I;16": 16}[mode]\n\n # calculate bytes per line and the extra padding if needed\n bits_per_line = bits_per_pixel * width\n full_bytes_per_line, remaining_bits_per_line = divmod(bits_per_line, 8)\n bytes_per_line = full_bytes_per_line + (1 if remaining_bits_per_line else 0)\n\n extra_padding = -bytes_per_line % 4\n\n # already 32 bit aligned by luck\n if not extra_padding:\n return bytes\n\n new_data = [\n bytes[i * bytes_per_line : (i + 1) * bytes_per_line] + b"\x00" * extra_padding\n for i in range(len(bytes) // bytes_per_line)\n ]\n\n return b"".join(new_data)\n\n\ndef _toqclass_helper(im: Image.Image | str | QByteArray) -> dict[str, Any]:\n data = None\n colortable = None\n exclusive_fp = False\n\n # handle filename, if given instead of image name\n if hasattr(im, "toUtf8"):\n # FIXME - is this really the best way to do this?\n im = str(im.toUtf8(), "utf-8")\n if is_path(im):\n im = Image.open(im)\n exclusive_fp = True\n assert isinstance(im, Image.Image)\n\n qt_format = getattr(QImage, "Format") if qt_version == "6" else QImage\n if im.mode == "1":\n format = getattr(qt_format, "Format_Mono")\n elif im.mode == "L":\n format = getattr(qt_format, "Format_Indexed8")\n colortable = [rgb(i, i, i) for i in range(256)]\n elif im.mode == "P":\n format = getattr(qt_format, "Format_Indexed8")\n palette = im.getpalette()\n assert palette is not None\n colortable = [rgb(*palette[i : i + 3]) for i in range(0, len(palette), 3)]\n elif im.mode == "RGB":\n # Populate the 4th channel with 255\n im = im.convert("RGBA")\n\n data = im.tobytes("raw", "BGRA")\n format = getattr(qt_format, "Format_RGB32")\n elif im.mode == "RGBA":\n data = im.tobytes("raw", "BGRA")\n format = getattr(qt_format, "Format_ARGB32")\n elif im.mode == "I;16":\n im = im.point(lambda i: i * 256)\n\n format = getattr(qt_format, "Format_Grayscale16")\n else:\n if exclusive_fp:\n im.close()\n msg = f"unsupported image mode {repr(im.mode)}"\n raise ValueError(msg)\n\n size = im.size\n __data = data or align8to32(im.tobytes(), size[0], im.mode)\n if exclusive_fp:\n im.close()\n return {"data": __data, "size": size, "format": format, "colortable": colortable}\n\n\nif qt_is_installed:\n\n class ImageQt(QImage): # type: ignore[misc]\n def __init__(self, im: Image.Image | str | QByteArray) -> None:\n """\n An PIL image wrapper for Qt. This is a subclass of PyQt's QImage\n class.\n\n :param im: A PIL Image object, or a file name (given either as\n Python string or a PyQt string object).\n """\n im_data = _toqclass_helper(im)\n # must keep a reference, or Qt will crash!\n # All QImage constructors that take data operate on an existing\n # buffer, so this buffer has to hang on for the life of the image.\n # Fixes https://github.com/python-pillow/Pillow/issues/1370\n self.__data = im_data["data"]\n super().__init__(\n self.__data,\n im_data["size"][0],\n im_data["size"][1],\n im_data["format"],\n )\n if im_data["colortable"]:\n self.setColorTable(im_data["colortable"])\n\n\ndef toqimage(im: Image.Image | str | QByteArray) -> ImageQt:\n return ImageQt(im)\n\n\ndef toqpixmap(im: Image.Image | str | QByteArray) -> QPixmap:\n qimage = toqimage(im)\n pixmap = getattr(QPixmap, "fromImage")(qimage)\n if qt_version == "6":\n pixmap.detach()\n return pixmap\n | .venv\Lib\site-packages\PIL\ImageQt.py | ImageQt.py | Python | 7,061 | 0.95 | 0.168182 | 0.17033 | node-utils | 299 | 2025-02-09T06:27:15.487823 | Apache-2.0 | false | 6276cd0501662cbaac82c13816a0ff71 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# sequence support classes\n#\n# history:\n# 1997-02-20 fl Created\n#\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\nfrom __future__ import annotations\n\nfrom typing import Callable\n\nfrom . import Image\n\n\nclass Iterator:\n """\n This class implements an iterator object that can be used to loop\n over an image sequence.\n\n You can use the ``[]`` operator to access elements by index. This operator\n will raise an :py:exc:`IndexError` if you try to access a nonexistent\n frame.\n\n :param im: An image object.\n """\n\n def __init__(self, im: Image.Image) -> None:\n if not hasattr(im, "seek"):\n msg = "im must have seek method"\n raise AttributeError(msg)\n self.im = im\n self.position = getattr(self.im, "_min_frame", 0)\n\n def __getitem__(self, ix: int) -> Image.Image:\n try:\n self.im.seek(ix)\n return self.im\n except EOFError as e:\n msg = "end of sequence"\n raise IndexError(msg) from e\n\n def __iter__(self) -> Iterator:\n return self\n\n def __next__(self) -> Image.Image:\n try:\n self.im.seek(self.position)\n self.position += 1\n return self.im\n except EOFError as e:\n msg = "end of sequence"\n raise StopIteration(msg) from e\n\n\ndef all_frames(\n im: Image.Image | list[Image.Image],\n func: Callable[[Image.Image], Image.Image] | None = None,\n) -> list[Image.Image]:\n """\n Applies a given function to all frames in an image or a list of images.\n The frames are returned as a list of separate images.\n\n :param im: An image, or a list of images.\n :param func: The function to apply to all of the image frames.\n :returns: A list of images.\n """\n if not isinstance(im, list):\n im = [im]\n\n ims = []\n for imSequence in im:\n current = imSequence.tell()\n\n ims += [im_frame.copy() for im_frame in Iterator(imSequence)]\n\n imSequence.seek(current)\n return [func(im) for im in ims] if func else ims\n | .venv\Lib\site-packages\PIL\ImageSequence.py | ImageSequence.py | Python | 2,286 | 0.95 | 0.232558 | 0.217391 | react-lib | 63 | 2023-11-15T20:37:10.395429 | GPL-3.0 | false | 32a062c8f8023e0c385cb5cd20f63234 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# im.show() drivers\n#\n# History:\n# 2008-04-06 fl Created\n#\n# Copyright (c) Secret Labs AB 2008.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport abc\nimport os\nimport shutil\nimport subprocess\nimport sys\nfrom shlex import quote\nfrom typing import Any\n\nfrom . import Image\n\n_viewers = []\n\n\ndef register(viewer: type[Viewer] | Viewer, order: int = 1) -> None:\n """\n The :py:func:`register` function is used to register additional viewers::\n\n from PIL import ImageShow\n ImageShow.register(MyViewer()) # MyViewer will be used as a last resort\n ImageShow.register(MySecondViewer(), 0) # MySecondViewer will be prioritised\n ImageShow.register(ImageShow.XVViewer(), 0) # XVViewer will be prioritised\n\n :param viewer: The viewer to be registered.\n :param order:\n Zero or a negative integer to prepend this viewer to the list,\n a positive integer to append it.\n """\n if isinstance(viewer, type) and issubclass(viewer, Viewer):\n viewer = viewer()\n if order > 0:\n _viewers.append(viewer)\n else:\n _viewers.insert(0, viewer)\n\n\ndef show(image: Image.Image, title: str | None = None, **options: Any) -> bool:\n r"""\n Display a given image.\n\n :param image: An image object.\n :param title: Optional title. Not all viewers can display the title.\n :param \**options: Additional viewer options.\n :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.\n """\n for viewer in _viewers:\n if viewer.show(image, title=title, **options):\n return True\n return False\n\n\nclass Viewer:\n """Base class for viewers."""\n\n # main api\n\n def show(self, image: Image.Image, **options: Any) -> int:\n """\n The main function for displaying an image.\n Converts the given image to the target format and displays it.\n """\n\n if not (\n image.mode in ("1", "RGBA")\n or (self.format == "PNG" and image.mode in ("I;16", "LA"))\n ):\n base = Image.getmodebase(image.mode)\n if image.mode != base:\n image = image.convert(base)\n\n return self.show_image(image, **options)\n\n # hook methods\n\n format: str | None = None\n """The format to convert the image into."""\n options: dict[str, Any] = {}\n """Additional options used to convert the image."""\n\n def get_format(self, image: Image.Image) -> str | None:\n """Return format name, or ``None`` to save as PGM/PPM."""\n return self.format\n\n def get_command(self, file: str, **options: Any) -> str:\n """\n Returns the command used to display the file.\n Not implemented in the base class.\n """\n msg = "unavailable in base viewer"\n raise NotImplementedError(msg)\n\n def save_image(self, image: Image.Image) -> str:\n """Save to temporary file and return filename."""\n return image._dump(format=self.get_format(image), **self.options)\n\n def show_image(self, image: Image.Image, **options: Any) -> int:\n """Display the given image."""\n return self.show_file(self.save_image(image), **options)\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n os.system(self.get_command(path, **options)) # nosec\n return 1\n\n\n# --------------------------------------------------------------------\n\n\nclass WindowsViewer(Viewer):\n """The default viewer on Windows is the default system application for PNG files."""\n\n format = "PNG"\n options = {"compress_level": 1, "save_all": True}\n\n def get_command(self, file: str, **options: Any) -> str:\n return (\n f'start "Pillow" /WAIT "{file}" '\n "&& ping -n 4 127.0.0.1 >NUL "\n f'&& del /f "{file}"'\n )\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n subprocess.Popen(\n self.get_command(path, **options),\n shell=True,\n creationflags=getattr(subprocess, "CREATE_NO_WINDOW"),\n ) # nosec\n return 1\n\n\nif sys.platform == "win32":\n register(WindowsViewer)\n\n\nclass MacViewer(Viewer):\n """The default viewer on macOS using ``Preview.app``."""\n\n format = "PNG"\n options = {"compress_level": 1, "save_all": True}\n\n def get_command(self, file: str, **options: Any) -> str:\n # on darwin open returns immediately resulting in the temp\n # file removal while app is opening\n command = "open -a Preview.app"\n command = f"({command} {quote(file)}; sleep 20; rm -f {quote(file)})&"\n return command\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n subprocess.call(["open", "-a", "Preview.app", path])\n\n pyinstaller = getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")\n executable = (not pyinstaller and sys.executable) or shutil.which("python3")\n if executable:\n subprocess.Popen(\n [\n executable,\n "-c",\n "import os, sys, time; time.sleep(20); os.remove(sys.argv[1])",\n path,\n ]\n )\n return 1\n\n\nif sys.platform == "darwin":\n register(MacViewer)\n\n\nclass UnixViewer(abc.ABC, Viewer):\n format = "PNG"\n options = {"compress_level": 1, "save_all": True}\n\n @abc.abstractmethod\n def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:\n pass\n\n def get_command(self, file: str, **options: Any) -> str:\n command = self.get_command_ex(file, **options)[0]\n return f"{command} {quote(file)}"\n\n\nclass XDGViewer(UnixViewer):\n """\n The freedesktop.org ``xdg-open`` command.\n """\n\n def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:\n command = executable = "xdg-open"\n return command, executable\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n subprocess.Popen(["xdg-open", path])\n return 1\n\n\nclass DisplayViewer(UnixViewer):\n """\n The ImageMagick ``display`` command.\n This viewer supports the ``title`` parameter.\n """\n\n def get_command_ex(\n self, file: str, title: str | None = None, **options: Any\n ) -> tuple[str, str]:\n command = executable = "display"\n if title:\n command += f" -title {quote(title)}"\n return command, executable\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n args = ["display"]\n title = options.get("title")\n if title:\n args += ["-title", title]\n args.append(path)\n\n subprocess.Popen(args)\n return 1\n\n\nclass GmDisplayViewer(UnixViewer):\n """The GraphicsMagick ``gm display`` command."""\n\n def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:\n executable = "gm"\n command = "gm display"\n return command, executable\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n subprocess.Popen(["gm", "display", path])\n return 1\n\n\nclass EogViewer(UnixViewer):\n """The GNOME Image Viewer ``eog`` command."""\n\n def get_command_ex(self, file: str, **options: Any) -> tuple[str, str]:\n executable = "eog"\n command = "eog -n"\n return command, executable\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n subprocess.Popen(["eog", "-n", path])\n return 1\n\n\nclass XVViewer(UnixViewer):\n """\n The X Viewer ``xv`` command.\n This viewer supports the ``title`` parameter.\n """\n\n def get_command_ex(\n self, file: str, title: str | None = None, **options: Any\n ) -> tuple[str, str]:\n # note: xv is pretty outdated. most modern systems have\n # imagemagick's display command instead.\n command = executable = "xv"\n if title:\n command += f" -name {quote(title)}"\n return command, executable\n\n def show_file(self, path: str, **options: Any) -> int:\n """\n Display given file.\n """\n if not os.path.exists(path):\n raise FileNotFoundError\n args = ["xv"]\n title = options.get("title")\n if title:\n args += ["-name", title]\n args.append(path)\n\n subprocess.Popen(args)\n return 1\n\n\nif sys.platform not in ("win32", "darwin"): # unixoids\n if shutil.which("xdg-open"):\n register(XDGViewer)\n if shutil.which("display"):\n register(DisplayViewer)\n if shutil.which("gm"):\n register(GmDisplayViewer)\n if shutil.which("eog"):\n register(EogViewer)\n if shutil.which("xv"):\n register(XVViewer)\n\n\nclass IPythonViewer(Viewer):\n """The viewer for IPython frontends."""\n\n def show_image(self, image: Image.Image, **options: Any) -> int:\n ipython_display(image)\n return 1\n\n\ntry:\n from IPython.display import display as ipython_display\nexcept ImportError:\n pass\nelse:\n register(IPythonViewer)\n\n\nif __name__ == "__main__":\n if len(sys.argv) < 2:\n print("Syntax: python3 ImageShow.py imagefile [title]")\n sys.exit()\n\n with Image.open(sys.argv[1]) as im:\n print(show(im, *sys.argv[2:]))\n | .venv\Lib\site-packages\PIL\ImageShow.py | ImageShow.py | Python | 10,468 | 0.95 | 0.209945 | 0.06993 | python-kit | 177 | 2025-02-02T14:54:40.189881 | Apache-2.0 | false | a392e2dad31691917768877e963ac1b8 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# global image statistics\n#\n# History:\n# 1996-04-05 fl Created\n# 1997-05-21 fl Added mask; added rms, var, stddev attributes\n# 1997-08-05 fl Added median\n# 1998-07-05 hk Fixed integer overflow error\n#\n# Notes:\n# This class shows how to implement delayed evaluation of attributes.\n# To get a certain value, simply access the corresponding attribute.\n# The __getattr__ dispatcher takes care of the rest.\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996-97.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport math\nfrom functools import cached_property\n\nfrom . import Image\n\n\nclass Stat:\n def __init__(\n self, image_or_list: Image.Image | list[int], mask: Image.Image | None = None\n ) -> None:\n """\n Calculate statistics for the given image. If a mask is included,\n only the regions covered by that mask are included in the\n statistics. You can also pass in a previously calculated histogram.\n\n :param image: A PIL image, or a precalculated histogram.\n\n .. note::\n\n For a PIL image, calculations rely on the\n :py:meth:`~PIL.Image.Image.histogram` method. The pixel counts are\n grouped into 256 bins, even if the image has more than 8 bits per\n channel. So ``I`` and ``F`` mode images have a maximum ``mean``,\n ``median`` and ``rms`` of 255, and cannot have an ``extrema`` maximum\n of more than 255.\n\n :param mask: An optional mask.\n """\n if isinstance(image_or_list, Image.Image):\n self.h = image_or_list.histogram(mask)\n elif isinstance(image_or_list, list):\n self.h = image_or_list\n else:\n msg = "first argument must be image or list" # type: ignore[unreachable]\n raise TypeError(msg)\n self.bands = list(range(len(self.h) // 256))\n\n @cached_property\n def extrema(self) -> list[tuple[int, int]]:\n """\n Min/max values for each band in the image.\n\n .. note::\n This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and\n simply returns the low and high bins used. This is correct for\n images with 8 bits per channel, but fails for other modes such as\n ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to\n return per-band extrema for the image. This is more correct and\n efficient because, for non-8-bit modes, the histogram method uses\n :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.\n """\n\n def minmax(histogram: list[int]) -> tuple[int, int]:\n res_min, res_max = 255, 0\n for i in range(256):\n if histogram[i]:\n res_min = i\n break\n for i in range(255, -1, -1):\n if histogram[i]:\n res_max = i\n break\n return res_min, res_max\n\n return [minmax(self.h[i:]) for i in range(0, len(self.h), 256)]\n\n @cached_property\n def count(self) -> list[int]:\n """Total number of pixels for each band in the image."""\n return [sum(self.h[i : i + 256]) for i in range(0, len(self.h), 256)]\n\n @cached_property\n def sum(self) -> list[float]:\n """Sum of all pixels for each band in the image."""\n\n v = []\n for i in range(0, len(self.h), 256):\n layer_sum = 0.0\n for j in range(256):\n layer_sum += j * self.h[i + j]\n v.append(layer_sum)\n return v\n\n @cached_property\n def sum2(self) -> list[float]:\n """Squared sum of all pixels for each band in the image."""\n\n v = []\n for i in range(0, len(self.h), 256):\n sum2 = 0.0\n for j in range(256):\n sum2 += (j**2) * float(self.h[i + j])\n v.append(sum2)\n return v\n\n @cached_property\n def mean(self) -> list[float]:\n """Average (arithmetic mean) pixel level for each band in the image."""\n return [self.sum[i] / self.count[i] for i in self.bands]\n\n @cached_property\n def median(self) -> list[int]:\n """Median pixel level for each band in the image."""\n\n v = []\n for i in self.bands:\n s = 0\n half = self.count[i] // 2\n b = i * 256\n for j in range(256):\n s = s + self.h[b + j]\n if s > half:\n break\n v.append(j)\n return v\n\n @cached_property\n def rms(self) -> list[float]:\n """RMS (root-mean-square) for each band in the image."""\n return [math.sqrt(self.sum2[i] / self.count[i]) for i in self.bands]\n\n @cached_property\n def var(self) -> list[float]:\n """Variance for each band in the image."""\n return [\n (self.sum2[i] - (self.sum[i] ** 2.0) / self.count[i]) / self.count[i]\n for i in self.bands\n ]\n\n @cached_property\n def stddev(self) -> list[float]:\n """Standard deviation for each band in the image."""\n return [math.sqrt(self.var[i]) for i in self.bands]\n\n\nGlobal = Stat # compatibility\n | .venv\Lib\site-packages\PIL\ImageStat.py | ImageStat.py | Python | 5,485 | 0.95 | 0.29375 | 0.162963 | awesome-app | 743 | 2025-06-22T21:43:42.536358 | Apache-2.0 | false | d3c641a1754d3dc48eb6aacde875f4ba |
#\n# The Python Imaging Library.\n# $Id$\n#\n# a Tk display interface\n#\n# History:\n# 96-04-08 fl Created\n# 96-09-06 fl Added getimage method\n# 96-11-01 fl Rewritten, removed image attribute and crop method\n# 97-05-09 fl Use PyImagingPaste method instead of image type\n# 97-05-12 fl Minor tweaks to match the IFUNC95 interface\n# 97-05-17 fl Support the "pilbitmap" booster patch\n# 97-06-05 fl Added file= and data= argument to image constructors\n# 98-03-09 fl Added width and height methods to Image classes\n# 98-07-02 fl Use default mode for "P" images without palette attribute\n# 98-07-02 fl Explicitly destroy Tkinter image objects\n# 99-07-24 fl Support multiple Tk interpreters (from Greg Couch)\n# 99-07-26 fl Automatically hook into Tkinter (if possible)\n# 99-08-15 fl Hook uses _imagingtk instead of _imaging\n#\n# Copyright (c) 1997-1999 by Secret Labs AB\n# Copyright (c) 1996-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport tkinter\nfrom io import BytesIO\nfrom typing import Any\n\nfrom . import Image, ImageFile\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from ._typing import CapsuleType\n\n# --------------------------------------------------------------------\n# Check for Tkinter interface hooks\n\n\ndef _get_image_from_kw(kw: dict[str, Any]) -> ImageFile.ImageFile | None:\n source = None\n if "file" in kw:\n source = kw.pop("file")\n elif "data" in kw:\n source = BytesIO(kw.pop("data"))\n if not source:\n return None\n return Image.open(source)\n\n\ndef _pyimagingtkcall(\n command: str, photo: PhotoImage | tkinter.PhotoImage, ptr: CapsuleType\n) -> None:\n tk = photo.tk\n try:\n tk.call(command, photo, repr(ptr))\n except tkinter.TclError:\n # activate Tkinter hook\n # may raise an error if it cannot attach to Tkinter\n from . import _imagingtk\n\n _imagingtk.tkinit(tk.interpaddr())\n tk.call(command, photo, repr(ptr))\n\n\n# --------------------------------------------------------------------\n# PhotoImage\n\n\nclass PhotoImage:\n """\n A Tkinter-compatible photo image. This can be used\n everywhere Tkinter expects an image object. If the image is an RGBA\n image, pixels having alpha 0 are treated as transparent.\n\n The constructor takes either a PIL image, or a mode and a size.\n Alternatively, you can use the ``file`` or ``data`` options to initialize\n the photo image object.\n\n :param image: Either a PIL image, or a mode string. If a mode string is\n used, a size must also be given.\n :param size: If the first argument is a mode string, this defines the size\n of the image.\n :keyword file: A filename to load the image from (using\n ``Image.open(file)``).\n :keyword data: An 8-bit string containing image data (as loaded from an\n image file).\n """\n\n def __init__(\n self,\n image: Image.Image | str | None = None,\n size: tuple[int, int] | None = None,\n **kw: Any,\n ) -> None:\n # Tk compatibility: file or data\n if image is None:\n image = _get_image_from_kw(kw)\n\n if image is None:\n msg = "Image is required"\n raise ValueError(msg)\n elif isinstance(image, str):\n mode = image\n image = None\n\n if size is None:\n msg = "If first argument is mode, size is required"\n raise ValueError(msg)\n else:\n # got an image instead of a mode\n mode = image.mode\n if mode == "P":\n # palette mapped data\n image.apply_transparency()\n image.load()\n mode = image.palette.mode if image.palette else "RGB"\n size = image.size\n kw["width"], kw["height"] = size\n\n if mode not in ["1", "L", "RGB", "RGBA"]:\n mode = Image.getmodebase(mode)\n\n self.__mode = mode\n self.__size = size\n self.__photo = tkinter.PhotoImage(**kw)\n self.tk = self.__photo.tk\n if image:\n self.paste(image)\n\n def __del__(self) -> None:\n try:\n name = self.__photo.name\n except AttributeError:\n return\n self.__photo.name = None\n try:\n self.__photo.tk.call("image", "delete", name)\n except Exception:\n pass # ignore internal errors\n\n def __str__(self) -> str:\n """\n Get the Tkinter photo image identifier. This method is automatically\n called by Tkinter whenever a PhotoImage object is passed to a Tkinter\n method.\n\n :return: A Tkinter photo image identifier (a string).\n """\n return str(self.__photo)\n\n def width(self) -> int:\n """\n Get the width of the image.\n\n :return: The width, in pixels.\n """\n return self.__size[0]\n\n def height(self) -> int:\n """\n Get the height of the image.\n\n :return: The height, in pixels.\n """\n return self.__size[1]\n\n def paste(self, im: Image.Image) -> None:\n """\n Paste a PIL image into the photo image. Note that this can\n be very slow if the photo image is displayed.\n\n :param im: A PIL image. The size must match the target region. If the\n mode does not match, the image is converted to the mode of\n the bitmap image.\n """\n # convert to blittable\n ptr = im.getim()\n image = im.im\n if not image.isblock() or im.mode != self.__mode:\n block = Image.core.new_block(self.__mode, im.size)\n image.convert2(block, image) # convert directly between buffers\n ptr = block.ptr\n\n _pyimagingtkcall("PyImagingPhoto", self.__photo, ptr)\n\n\n# --------------------------------------------------------------------\n# BitmapImage\n\n\nclass BitmapImage:\n """\n A Tkinter-compatible bitmap image. This can be used everywhere Tkinter\n expects an image object.\n\n The given image must have mode "1". Pixels having value 0 are treated as\n transparent. Options, if any, are passed on to Tkinter. The most commonly\n used option is ``foreground``, which is used to specify the color for the\n non-transparent parts. See the Tkinter documentation for information on\n how to specify colours.\n\n :param image: A PIL image.\n """\n\n def __init__(self, image: Image.Image | None = None, **kw: Any) -> None:\n # Tk compatibility: file or data\n if image is None:\n image = _get_image_from_kw(kw)\n\n if image is None:\n msg = "Image is required"\n raise ValueError(msg)\n self.__mode = image.mode\n self.__size = image.size\n\n self.__photo = tkinter.BitmapImage(data=image.tobitmap(), **kw)\n\n def __del__(self) -> None:\n try:\n name = self.__photo.name\n except AttributeError:\n return\n self.__photo.name = None\n try:\n self.__photo.tk.call("image", "delete", name)\n except Exception:\n pass # ignore internal errors\n\n def width(self) -> int:\n """\n Get the width of the image.\n\n :return: The width, in pixels.\n """\n return self.__size[0]\n\n def height(self) -> int:\n """\n Get the height of the image.\n\n :return: The height, in pixels.\n """\n return self.__size[1]\n\n def __str__(self) -> str:\n """\n Get the Tkinter bitmap image identifier. This method is automatically\n called by Tkinter whenever a BitmapImage object is passed to a Tkinter\n method.\n\n :return: A Tkinter bitmap image identifier (a string).\n """\n return str(self.__photo)\n\n\ndef getimage(photo: PhotoImage) -> Image.Image:\n """Copies the contents of a PhotoImage to a PIL image memory."""\n im = Image.new("RGBA", (photo.width(), photo.height()))\n\n _pyimagingtkcall("PyImagingPhotoGet", photo, im.getim())\n\n return im\n | .venv\Lib\site-packages\PIL\ImageTk.py | ImageTk.py | Python | 8,398 | 0.95 | 0.161654 | 0.185185 | react-lib | 376 | 2024-09-10T17:07:51.980345 | Apache-2.0 | false | 23e172c47fec0baa7cf1f6597f72dd35 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# transform wrappers\n#\n# History:\n# 2002-04-08 fl Created\n#\n# Copyright (c) 2002 by Secret Labs AB\n# Copyright (c) 2002 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any\n\nfrom . import Image\n\n\nclass Transform(Image.ImageTransformHandler):\n """Base class for other transforms defined in :py:mod:`~PIL.ImageTransform`."""\n\n method: Image.Transform\n\n def __init__(self, data: Sequence[Any]) -> None:\n self.data = data\n\n def getdata(self) -> tuple[Image.Transform, Sequence[int]]:\n return self.method, self.data\n\n def transform(\n self,\n size: tuple[int, int],\n image: Image.Image,\n **options: Any,\n ) -> Image.Image:\n """Perform the transform. Called from :py:meth:`.Image.transform`."""\n # can be overridden\n method, data = self.getdata()\n return image.transform(size, method, data, **options)\n\n\nclass AffineTransform(Transform):\n """\n Define an affine image transform.\n\n This function takes a 6-tuple (a, b, c, d, e, f) which contain the first\n two rows from the inverse of an affine transform matrix. For each pixel\n (x, y) in the output image, the new value is taken from a position (a x +\n b y + c, d x + e y + f) in the input image, rounded to nearest pixel.\n\n This function can be used to scale, translate, rotate, and shear the\n original image.\n\n See :py:meth:`.Image.transform`\n\n :param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows\n from the inverse of an affine transform matrix.\n """\n\n method = Image.Transform.AFFINE\n\n\nclass PerspectiveTransform(Transform):\n """\n Define a perspective image transform.\n\n This function takes an 8-tuple (a, b, c, d, e, f, g, h). For each pixel\n (x, y) in the output image, the new value is taken from a position\n ((a x + b y + c) / (g x + h y + 1), (d x + e y + f) / (g x + h y + 1)) in\n the input image, rounded to nearest pixel.\n\n This function can be used to scale, translate, rotate, and shear the\n original image.\n\n See :py:meth:`.Image.transform`\n\n :param matrix: An 8-tuple (a, b, c, d, e, f, g, h).\n """\n\n method = Image.Transform.PERSPECTIVE\n\n\nclass ExtentTransform(Transform):\n """\n Define a transform to extract a subregion from an image.\n\n Maps a rectangle (defined by two corners) from the image to a rectangle of\n the given size. The resulting image will contain data sampled from between\n the corners, such that (x0, y0) in the input image will end up at (0,0) in\n the output image, and (x1, y1) at size.\n\n This method can be used to crop, stretch, shrink, or mirror an arbitrary\n rectangle in the current image. It is slightly slower than crop, but about\n as fast as a corresponding resize operation.\n\n See :py:meth:`.Image.transform`\n\n :param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the\n input image's coordinate system. See :ref:`coordinate-system`.\n """\n\n method = Image.Transform.EXTENT\n\n\nclass QuadTransform(Transform):\n """\n Define a quad image transform.\n\n Maps a quadrilateral (a region defined by four corners) from the image to a\n rectangle of the given size.\n\n See :py:meth:`.Image.transform`\n\n :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the\n upper left, lower left, lower right, and upper right corner of the\n source quadrilateral.\n """\n\n method = Image.Transform.QUAD\n\n\nclass MeshTransform(Transform):\n """\n Define a mesh image transform. A mesh transform consists of one or more\n individual quad transforms.\n\n See :py:meth:`.Image.transform`\n\n :param data: A list of (bbox, quad) tuples.\n """\n\n method = Image.Transform.MESH\n | .venv\Lib\site-packages\PIL\ImageTransform.py | ImageTransform.py | Python | 4,052 | 0.95 | 0.117647 | 0.166667 | awesome-app | 900 | 2024-09-14T05:20:04.079959 | BSD-3-Clause | false | 86f33ef9ba067de96b7dd946df735c9e |
#\n# The Python Imaging Library.\n# $Id$\n#\n# a Windows DIB display interface\n#\n# History:\n# 1996-05-20 fl Created\n# 1996-09-20 fl Fixed subregion exposure\n# 1997-09-21 fl Added draw primitive (for tzPrint)\n# 2003-05-21 fl Added experimental Window/ImageWindow classes\n# 2003-09-05 fl Added fromstring/tostring methods\n#\n# Copyright (c) Secret Labs AB 1997-2003.\n# Copyright (c) Fredrik Lundh 1996-2003.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image\n\n\nclass HDC:\n """\n Wraps an HDC integer. The resulting object can be passed to the\n :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`\n methods.\n """\n\n def __init__(self, dc: int) -> None:\n self.dc = dc\n\n def __int__(self) -> int:\n return self.dc\n\n\nclass HWND:\n """\n Wraps an HWND integer. The resulting object can be passed to the\n :py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`\n methods, instead of a DC.\n """\n\n def __init__(self, wnd: int) -> None:\n self.wnd = wnd\n\n def __int__(self) -> int:\n return self.wnd\n\n\nclass Dib:\n """\n A Windows bitmap with the given mode and size. The mode can be one of "1",\n "L", "P", or "RGB".\n\n If the display requires a palette, this constructor creates a suitable\n palette and associates it with the image. For an "L" image, 128 graylevels\n are allocated. For an "RGB" image, a 6x6x6 colour cube is used, together\n with 20 graylevels.\n\n To make sure that palettes work properly under Windows, you must call the\n ``palette`` method upon certain events from Windows.\n\n :param image: Either a PIL image, or a mode string. If a mode string is\n used, a size must also be given. The mode can be one of "1",\n "L", "P", or "RGB".\n :param size: If the first argument is a mode string, this\n defines the size of the image.\n """\n\n def __init__(\n self, image: Image.Image | str, size: tuple[int, int] | None = None\n ) -> None:\n if isinstance(image, str):\n mode = image\n image = ""\n if size is None:\n msg = "If first argument is mode, size is required"\n raise ValueError(msg)\n else:\n mode = image.mode\n size = image.size\n if mode not in ["1", "L", "P", "RGB"]:\n mode = Image.getmodebase(mode)\n self.image = Image.core.display(mode, size)\n self.mode = mode\n self.size = size\n if image:\n assert not isinstance(image, str)\n self.paste(image)\n\n def expose(self, handle: int | HDC | HWND) -> None:\n """\n Copy the bitmap contents to a device context.\n\n :param handle: Device context (HDC), cast to a Python integer, or an\n HDC or HWND instance. In PythonWin, you can use\n ``CDC.GetHandleAttrib()`` to get a suitable handle.\n """\n handle_int = int(handle)\n if isinstance(handle, HWND):\n dc = self.image.getdc(handle_int)\n try:\n self.image.expose(dc)\n finally:\n self.image.releasedc(handle_int, dc)\n else:\n self.image.expose(handle_int)\n\n def draw(\n self,\n handle: int | HDC | HWND,\n dst: tuple[int, int, int, int],\n src: tuple[int, int, int, int] | None = None,\n ) -> None:\n """\n Same as expose, but allows you to specify where to draw the image, and\n what part of it to draw.\n\n The destination and source areas are given as 4-tuple rectangles. If\n the source is omitted, the entire image is copied. If the source and\n the destination have different sizes, the image is resized as\n necessary.\n """\n if src is None:\n src = (0, 0) + self.size\n handle_int = int(handle)\n if isinstance(handle, HWND):\n dc = self.image.getdc(handle_int)\n try:\n self.image.draw(dc, dst, src)\n finally:\n self.image.releasedc(handle_int, dc)\n else:\n self.image.draw(handle_int, dst, src)\n\n def query_palette(self, handle: int | HDC | HWND) -> int:\n """\n Installs the palette associated with the image in the given device\n context.\n\n This method should be called upon **QUERYNEWPALETTE** and\n **PALETTECHANGED** events from Windows. If this method returns a\n non-zero value, one or more display palette entries were changed, and\n the image should be redrawn.\n\n :param handle: Device context (HDC), cast to a Python integer, or an\n HDC or HWND instance.\n :return: The number of entries that were changed (if one or more entries,\n this indicates that the image should be redrawn).\n """\n handle_int = int(handle)\n if isinstance(handle, HWND):\n handle = self.image.getdc(handle_int)\n try:\n result = self.image.query_palette(handle)\n finally:\n self.image.releasedc(handle, handle)\n else:\n result = self.image.query_palette(handle_int)\n return result\n\n def paste(\n self, im: Image.Image, box: tuple[int, int, int, int] | None = None\n ) -> None:\n """\n Paste a PIL image into the bitmap image.\n\n :param im: A PIL image. The size must match the target region.\n If the mode does not match, the image is converted to the\n mode of the bitmap image.\n :param box: A 4-tuple defining the left, upper, right, and\n lower pixel coordinate. See :ref:`coordinate-system`. If\n None is given instead of a tuple, all of the image is\n assumed.\n """\n im.load()\n if self.mode != im.mode:\n im = im.convert(self.mode)\n if box:\n self.image.paste(im.im, box)\n else:\n self.image.paste(im.im)\n\n def frombytes(self, buffer: bytes) -> None:\n """\n Load display memory contents from byte data.\n\n :param buffer: A buffer containing display data (usually\n data returned from :py:func:`~PIL.ImageWin.Dib.tobytes`)\n """\n self.image.frombytes(buffer)\n\n def tobytes(self) -> bytes:\n """\n Copy display memory contents to bytes object.\n\n :return: A bytes object containing display data.\n """\n return self.image.tobytes()\n\n\nclass Window:\n """Create a Window with the given title size."""\n\n def __init__(\n self, title: str = "PIL", width: int | None = None, height: int | None = None\n ) -> None:\n self.hwnd = Image.core.createwindow(\n title, self.__dispatcher, width or 0, height or 0\n )\n\n def __dispatcher(self, action: str, *args: int) -> None:\n getattr(self, f"ui_handle_{action}")(*args)\n\n def ui_handle_clear(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:\n pass\n\n def ui_handle_damage(self, x0: int, y0: int, x1: int, y1: int) -> None:\n pass\n\n def ui_handle_destroy(self) -> None:\n pass\n\n def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:\n pass\n\n def ui_handle_resize(self, width: int, height: int) -> None:\n pass\n\n def mainloop(self) -> None:\n Image.core.eventloop()\n\n\nclass ImageWindow(Window):\n """Create an image window which displays the given image."""\n\n def __init__(self, image: Image.Image | Dib, title: str = "PIL") -> None:\n if not isinstance(image, Dib):\n image = Dib(image)\n self.image = image\n width, height = image.size\n super().__init__(title, width=width, height=height)\n\n def ui_handle_repair(self, dc: int, x0: int, y0: int, x1: int, y1: int) -> None:\n self.image.draw(dc, (x0, y0, x1, y1))\n | .venv\Lib\site-packages\PIL\ImageWin.py | ImageWin.py | Python | 8,332 | 0.95 | 0.174089 | 0.092683 | python-kit | 906 | 2024-02-23T06:39:22.879225 | GPL-3.0 | false | ac17cd770de0aa86075fce91441e329c |
#\n# The Python Imaging Library.\n# $Id$\n#\n# IFUNC IM file handling for PIL\n#\n# history:\n# 1995-09-01 fl Created.\n# 1997-01-03 fl Save palette images\n# 1997-01-08 fl Added sequence support\n# 1997-01-23 fl Added P and RGB save support\n# 1997-05-31 fl Read floating point images\n# 1997-06-22 fl Save floating point images\n# 1997-08-27 fl Read and save 1-bit images\n# 1998-06-25 fl Added support for RGB+LUT images\n# 1998-07-02 fl Added support for YCC images\n# 1998-07-15 fl Renamed offset attribute to avoid name clash\n# 1998-12-29 fl Added I;16 support\n# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)\n# 2003-09-26 fl Added LA/PA support\n#\n# Copyright (c) 1997-2003 by Secret Labs AB.\n# Copyright (c) 1995-2001 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport os\nimport re\nfrom typing import IO, Any\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._util import DeferredError\n\n# --------------------------------------------------------------------\n# Standard tags\n\nCOMMENT = "Comment"\nDATE = "Date"\nEQUIPMENT = "Digitalization equipment"\nFRAMES = "File size (no of images)"\nLUT = "Lut"\nNAME = "Name"\nSCALE = "Scale (x,y)"\nSIZE = "Image size (x*y)"\nMODE = "Image type"\n\nTAGS = {\n COMMENT: 0,\n DATE: 0,\n EQUIPMENT: 0,\n FRAMES: 0,\n LUT: 0,\n NAME: 0,\n SCALE: 0,\n SIZE: 0,\n MODE: 0,\n}\n\nOPEN = {\n # ifunc93/p3cfunc formats\n "0 1 image": ("1", "1"),\n "L 1 image": ("1", "1"),\n "Greyscale image": ("L", "L"),\n "Grayscale image": ("L", "L"),\n "RGB image": ("RGB", "RGB;L"),\n "RLB image": ("RGB", "RLB"),\n "RYB image": ("RGB", "RLB"),\n "B1 image": ("1", "1"),\n "B2 image": ("P", "P;2"),\n "B4 image": ("P", "P;4"),\n "X 24 image": ("RGB", "RGB"),\n "L 32 S image": ("I", "I;32"),\n "L 32 F image": ("F", "F;32"),\n # old p3cfunc formats\n "RGB3 image": ("RGB", "RGB;T"),\n "RYB3 image": ("RGB", "RYB;T"),\n # extensions\n "LA image": ("LA", "LA;L"),\n "PA image": ("LA", "PA;L"),\n "RGBA image": ("RGBA", "RGBA;L"),\n "RGBX image": ("RGB", "RGBX;L"),\n "CMYK image": ("CMYK", "CMYK;L"),\n "YCC image": ("YCbCr", "YCbCr;L"),\n}\n\n# ifunc95 extensions\nfor i in ["8", "8S", "16", "16S", "32", "32F"]:\n OPEN[f"L {i} image"] = ("F", f"F;{i}")\n OPEN[f"L*{i} image"] = ("F", f"F;{i}")\nfor i in ["16", "16L", "16B"]:\n OPEN[f"L {i} image"] = (f"I;{i}", f"I;{i}")\n OPEN[f"L*{i} image"] = (f"I;{i}", f"I;{i}")\nfor i in ["32S"]:\n OPEN[f"L {i} image"] = ("I", f"I;{i}")\n OPEN[f"L*{i} image"] = ("I", f"I;{i}")\nfor j in range(2, 33):\n OPEN[f"L*{j} image"] = ("F", f"F;{j}")\n\n\n# --------------------------------------------------------------------\n# Read IM directory\n\nsplit = re.compile(rb"^([A-Za-z][^:]*):[ \t]*(.*)[ \t]*$")\n\n\ndef number(s: Any) -> float:\n try:\n return int(s)\n except ValueError:\n return float(s)\n\n\n##\n# Image plugin for the IFUNC IM file format.\n\n\nclass ImImageFile(ImageFile.ImageFile):\n format = "IM"\n format_description = "IFUNC Image Memory"\n _close_exclusive_fp_after_loading = False\n\n def _open(self) -> None:\n # Quick rejection: if there's not an LF among the first\n # 100 bytes, this is (probably) not a text header.\n\n if b"\n" not in self.fp.read(100):\n msg = "not an IM file"\n raise SyntaxError(msg)\n self.fp.seek(0)\n\n n = 0\n\n # Default values\n self.info[MODE] = "L"\n self.info[SIZE] = (512, 512)\n self.info[FRAMES] = 1\n\n self.rawmode = "L"\n\n while True:\n s = self.fp.read(1)\n\n # Some versions of IFUNC uses \n\r instead of \r\n...\n if s == b"\r":\n continue\n\n if not s or s == b"\0" or s == b"\x1a":\n break\n\n # FIXME: this may read whole file if not a text file\n s = s + self.fp.readline()\n\n if len(s) > 100:\n msg = "not an IM file"\n raise SyntaxError(msg)\n\n if s.endswith(b"\r\n"):\n s = s[:-2]\n elif s.endswith(b"\n"):\n s = s[:-1]\n\n try:\n m = split.match(s)\n except re.error as e:\n msg = "not an IM file"\n raise SyntaxError(msg) from e\n\n if m:\n k, v = m.group(1, 2)\n\n # Don't know if this is the correct encoding,\n # but a decent guess (I guess)\n k = k.decode("latin-1", "replace")\n v = v.decode("latin-1", "replace")\n\n # Convert value as appropriate\n if k in [FRAMES, SCALE, SIZE]:\n v = v.replace("*", ",")\n v = tuple(map(number, v.split(",")))\n if len(v) == 1:\n v = v[0]\n elif k == MODE and v in OPEN:\n v, self.rawmode = OPEN[v]\n\n # Add to dictionary. Note that COMMENT tags are\n # combined into a list of strings.\n if k == COMMENT:\n if k in self.info:\n self.info[k].append(v)\n else:\n self.info[k] = [v]\n else:\n self.info[k] = v\n\n if k in TAGS:\n n += 1\n\n else:\n msg = f"Syntax error in IM header: {s.decode('ascii', 'replace')}"\n raise SyntaxError(msg)\n\n if not n:\n msg = "Not an IM file"\n raise SyntaxError(msg)\n\n # Basic attributes\n self._size = self.info[SIZE]\n self._mode = self.info[MODE]\n\n # Skip forward to start of image data\n while s and not s.startswith(b"\x1a"):\n s = self.fp.read(1)\n if not s:\n msg = "File truncated"\n raise SyntaxError(msg)\n\n if LUT in self.info:\n # convert lookup table to palette or lut attribute\n palette = self.fp.read(768)\n greyscale = 1 # greyscale palette\n linear = 1 # linear greyscale palette\n for i in range(256):\n if palette[i] == palette[i + 256] == palette[i + 512]:\n if palette[i] != i:\n linear = 0\n else:\n greyscale = 0\n if self.mode in ["L", "LA", "P", "PA"]:\n if greyscale:\n if not linear:\n self.lut = list(palette[:256])\n else:\n if self.mode in ["L", "P"]:\n self._mode = self.rawmode = "P"\n elif self.mode in ["LA", "PA"]:\n self._mode = "PA"\n self.rawmode = "PA;L"\n self.palette = ImagePalette.raw("RGB;L", palette)\n elif self.mode == "RGB":\n if not greyscale or not linear:\n self.lut = list(palette)\n\n self.frame = 0\n\n self.__offset = offs = self.fp.tell()\n\n self._fp = self.fp # FIXME: hack\n\n if self.rawmode.startswith("F;"):\n # ifunc95 formats\n try:\n # use bit decoder (if necessary)\n bits = int(self.rawmode[2:])\n if bits not in [8, 16, 32]:\n self.tile = [\n ImageFile._Tile(\n "bit", (0, 0) + self.size, offs, (bits, 8, 3, 0, -1)\n )\n ]\n return\n except ValueError:\n pass\n\n if self.rawmode in ["RGB;T", "RYB;T"]:\n # Old LabEye/3PC files. Would be very surprised if anyone\n # ever stumbled upon such a file ;-)\n size = self.size[0] * self.size[1]\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, offs, ("G", 0, -1)),\n ImageFile._Tile("raw", (0, 0) + self.size, offs + size, ("R", 0, -1)),\n ImageFile._Tile(\n "raw", (0, 0) + self.size, offs + 2 * size, ("B", 0, -1)\n ),\n ]\n else:\n # LabEye/IFUNC files\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))\n ]\n\n @property\n def n_frames(self) -> int:\n return self.info[FRAMES]\n\n @property\n def is_animated(self) -> bool:\n return self.info[FRAMES] > 1\n\n def seek(self, frame: int) -> None:\n if not self._seek_check(frame):\n return\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n\n self.frame = frame\n\n if self.mode == "1":\n bits = 1\n else:\n bits = 8 * len(self.mode)\n\n size = ((self.size[0] * bits + 7) // 8) * self.size[1]\n offs = self.__offset + frame * size\n\n self.fp = self._fp\n\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, offs, (self.rawmode, 0, -1))\n ]\n\n def tell(self) -> int:\n return self.frame\n\n\n#\n# --------------------------------------------------------------------\n# Save IM files\n\n\nSAVE = {\n # mode: (im type, raw mode)\n "1": ("0 1", "1"),\n "L": ("Greyscale", "L"),\n "LA": ("LA", "LA;L"),\n "P": ("Greyscale", "P"),\n "PA": ("LA", "PA;L"),\n "I": ("L 32S", "I;32S"),\n "I;16": ("L 16", "I;16"),\n "I;16L": ("L 16L", "I;16L"),\n "I;16B": ("L 16B", "I;16B"),\n "F": ("L 32F", "F;32F"),\n "RGB": ("RGB", "RGB;L"),\n "RGBA": ("RGBA", "RGBA;L"),\n "RGBX": ("RGBX", "RGBX;L"),\n "CMYK": ("CMYK", "CMYK;L"),\n "YCbCr": ("YCC", "YCbCr;L"),\n}\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n try:\n image_type, rawmode = SAVE[im.mode]\n except KeyError as e:\n msg = f"Cannot save {im.mode} images as IM"\n raise ValueError(msg) from e\n\n frames = im.encoderinfo.get("frames", 1)\n\n fp.write(f"Image type: {image_type} image\r\n".encode("ascii"))\n if filename:\n # Each line must be 100 characters or less,\n # or: SyntaxError("not an IM file")\n # 8 characters are used for "Name: " and "\r\n"\n # Keep just the filename, ditch the potentially overlong path\n if isinstance(filename, bytes):\n filename = filename.decode("ascii")\n name, ext = os.path.splitext(os.path.basename(filename))\n name = "".join([name[: 92 - len(ext)], ext])\n\n fp.write(f"Name: {name}\r\n".encode("ascii"))\n fp.write(f"Image size (x*y): {im.size[0]}*{im.size[1]}\r\n".encode("ascii"))\n fp.write(f"File size (no of images): {frames}\r\n".encode("ascii"))\n if im.mode in ["P", "PA"]:\n fp.write(b"Lut: 1\r\n")\n fp.write(b"\000" * (511 - fp.tell()) + b"\032")\n if im.mode in ["P", "PA"]:\n im_palette = im.im.getpalette("RGB", "RGB;L")\n colors = len(im_palette) // 3\n palette = b""\n for i in range(3):\n palette += im_palette[colors * i : colors * (i + 1)]\n palette += b"\x00" * (256 - colors)\n fp.write(palette) # 768 bytes\n ImageFile._save(\n im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))]\n )\n\n\n#\n# --------------------------------------------------------------------\n# Registry\n\n\nImage.register_open(ImImageFile.format, ImImageFile)\nImage.register_save(ImImageFile.format, _save)\n\nImage.register_extension(ImImageFile.format, ".im")\n | .venv\Lib\site-packages\PIL\ImImagePlugin.py | ImImagePlugin.py | Python | 11,956 | 0.95 | 0.159383 | 0.201238 | awesome-app | 149 | 2023-08-21T17:11:38.978794 | BSD-3-Clause | false | 742f4261c0d2a2b52bdfc3009ee90891 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# IM Tools support for PIL\n#\n# history:\n# 1996-05-27 fl Created (read 8-bit images only)\n# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.2)\n#\n# Copyright (c) Secret Labs AB 1997-2001.\n# Copyright (c) Fredrik Lundh 1996-2001.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport re\n\nfrom . import Image, ImageFile\n\n#\n# --------------------------------------------------------------------\n\nfield = re.compile(rb"([a-z]*) ([^ \r\n]*)")\n\n\n##\n# Image plugin for IM Tools images.\n\n\nclass ImtImageFile(ImageFile.ImageFile):\n format = "IMT"\n format_description = "IM Tools"\n\n def _open(self) -> None:\n # Quick rejection: if there's not a LF among the first\n # 100 bytes, this is (probably) not a text header.\n\n assert self.fp is not None\n\n buffer = self.fp.read(100)\n if b"\n" not in buffer:\n msg = "not an IM file"\n raise SyntaxError(msg)\n\n xsize = ysize = 0\n\n while True:\n if buffer:\n s = buffer[:1]\n buffer = buffer[1:]\n else:\n s = self.fp.read(1)\n if not s:\n break\n\n if s == b"\x0c":\n # image data begins\n self.tile = [\n ImageFile._Tile(\n "raw",\n (0, 0) + self.size,\n self.fp.tell() - len(buffer),\n self.mode,\n )\n ]\n\n break\n\n else:\n # read key/value pair\n if b"\n" not in buffer:\n buffer += self.fp.read(100)\n lines = buffer.split(b"\n")\n s += lines.pop(0)\n buffer = b"\n".join(lines)\n if len(s) == 1 or len(s) > 100:\n break\n if s[0] == ord(b"*"):\n continue # comment\n\n m = field.match(s)\n if not m:\n break\n k, v = m.group(1, 2)\n if k == b"width":\n xsize = int(v)\n self._size = xsize, ysize\n elif k == b"height":\n ysize = int(v)\n self._size = xsize, ysize\n elif k == b"pixel" and v == b"n8":\n self._mode = "L"\n\n\n#\n# --------------------------------------------------------------------\n\nImage.register_open(ImtImageFile.format, ImtImageFile)\n\n#\n# no extension registered (".im" is simply too common)\n | .venv\Lib\site-packages\PIL\ImtImagePlugin.py | ImtImagePlugin.py | Python | 2,768 | 0.95 | 0.15534 | 0.329268 | awesome-app | 931 | 2024-04-13T07:34:31.216990 | Apache-2.0 | false | ea07cfa3f1e2771727ac83d1c32802f2 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# IPTC/NAA file handling\n#\n# history:\n# 1995-10-01 fl Created\n# 1998-03-09 fl Cleaned up and added to PIL\n# 2002-06-18 fl Added getiptcinfo helper\n#\n# Copyright (c) Secret Labs AB 1997-2002.\n# Copyright (c) Fredrik Lundh 1995.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom io import BytesIO\nfrom typing import cast\n\nfrom . import Image, ImageFile\nfrom ._binary import i16be as i16\nfrom ._binary import i32be as i32\nfrom ._deprecate import deprecate\n\nCOMPRESSION = {1: "raw", 5: "jpeg"}\n\n\ndef __getattr__(name: str) -> bytes:\n if name == "PAD":\n deprecate("IptcImagePlugin.PAD", 12)\n return b"\0\0\0\0"\n msg = f"module '{__name__}' has no attribute '{name}'"\n raise AttributeError(msg)\n\n\n#\n# Helpers\n\n\ndef _i(c: bytes) -> int:\n return i32((b"\0\0\0\0" + c)[-4:])\n\n\ndef _i8(c: int | bytes) -> int:\n return c if isinstance(c, int) else c[0]\n\n\ndef i(c: bytes) -> int:\n """.. deprecated:: 10.2.0"""\n deprecate("IptcImagePlugin.i", 12)\n return _i(c)\n\n\ndef dump(c: Sequence[int | bytes]) -> None:\n """.. deprecated:: 10.2.0"""\n deprecate("IptcImagePlugin.dump", 12)\n for i in c:\n print(f"{_i8(i):02x}", end=" ")\n print()\n\n\n##\n# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields\n# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.\n\n\nclass IptcImageFile(ImageFile.ImageFile):\n format = "IPTC"\n format_description = "IPTC/NAA"\n\n def getint(self, key: tuple[int, int]) -> int:\n return _i(self.info[key])\n\n def field(self) -> tuple[tuple[int, int] | None, int]:\n #\n # get a IPTC field header\n s = self.fp.read(5)\n if not s.strip(b"\x00"):\n return None, 0\n\n tag = s[1], s[2]\n\n # syntax\n if s[0] != 0x1C or tag[0] not in [1, 2, 3, 4, 5, 6, 7, 8, 9, 240]:\n msg = "invalid IPTC/NAA file"\n raise SyntaxError(msg)\n\n # field size\n size = s[3]\n if size > 132:\n msg = "illegal field length in IPTC/NAA file"\n raise OSError(msg)\n elif size == 128:\n size = 0\n elif size > 128:\n size = _i(self.fp.read(size - 128))\n else:\n size = i16(s, 3)\n\n return tag, size\n\n def _open(self) -> None:\n # load descriptive fields\n while True:\n offset = self.fp.tell()\n tag, size = self.field()\n if not tag or tag == (8, 10):\n break\n if size:\n tagdata = self.fp.read(size)\n else:\n tagdata = None\n if tag in self.info:\n if isinstance(self.info[tag], list):\n self.info[tag].append(tagdata)\n else:\n self.info[tag] = [self.info[tag], tagdata]\n else:\n self.info[tag] = tagdata\n\n # mode\n layers = self.info[(3, 60)][0]\n component = self.info[(3, 60)][1]\n if (3, 65) in self.info:\n id = self.info[(3, 65)][0] - 1\n else:\n id = 0\n if layers == 1 and not component:\n self._mode = "L"\n elif layers == 3 and component:\n self._mode = "RGB"[id]\n elif layers == 4 and component:\n self._mode = "CMYK"[id]\n\n # size\n self._size = self.getint((3, 20)), self.getint((3, 30))\n\n # compression\n try:\n compression = COMPRESSION[self.getint((3, 120))]\n except KeyError as e:\n msg = "Unknown IPTC image compression"\n raise OSError(msg) from e\n\n # tile\n if tag == (8, 10):\n self.tile = [\n ImageFile._Tile("iptc", (0, 0) + self.size, offset, compression)\n ]\n\n def load(self) -> Image.core.PixelAccess | None:\n if len(self.tile) != 1 or self.tile[0][0] != "iptc":\n return ImageFile.ImageFile.load(self)\n\n offset, compression = self.tile[0][2:]\n\n self.fp.seek(offset)\n\n # Copy image data to temporary file\n o = BytesIO()\n if compression == "raw":\n # To simplify access to the extracted file,\n # prepend a PPM header\n o.write(b"P5\n%d %d\n255\n" % self.size)\n while True:\n type, size = self.field()\n if type != (8, 10):\n break\n while size > 0:\n s = self.fp.read(min(size, 8192))\n if not s:\n break\n o.write(s)\n size -= len(s)\n\n with Image.open(o) as _im:\n _im.load()\n self.im = _im.im\n self.tile = []\n return Image.Image.load(self)\n\n\nImage.register_open(IptcImageFile.format, IptcImageFile)\n\nImage.register_extension(IptcImageFile.format, ".iim")\n\n\ndef getiptcinfo(\n im: ImageFile.ImageFile,\n) -> dict[tuple[int, int], bytes | list[bytes]] | None:\n """\n Get IPTC information from TIFF, JPEG, or IPTC file.\n\n :param im: An image containing IPTC data.\n :returns: A dictionary containing IPTC information, or None if\n no IPTC information block was found.\n """\n from . import JpegImagePlugin, TiffImagePlugin\n\n data = None\n\n info: dict[tuple[int, int], bytes | list[bytes]] = {}\n if isinstance(im, IptcImageFile):\n # return info dictionary right away\n for k, v in im.info.items():\n if isinstance(k, tuple):\n info[k] = v\n return info\n\n elif isinstance(im, JpegImagePlugin.JpegImageFile):\n # extract the IPTC/NAA resource\n photoshop = im.info.get("photoshop")\n if photoshop:\n data = photoshop.get(0x0404)\n\n elif isinstance(im, TiffImagePlugin.TiffImageFile):\n # get raw data from the IPTC/NAA tag (PhotoShop tags the data\n # as 4-byte integers, so we cannot use the get method...)\n try:\n data = im.tag_v2._tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]\n except KeyError:\n pass\n\n if data is None:\n return None # no properties\n\n # create an IptcImagePlugin object without initializing it\n class FakeImage:\n pass\n\n fake_im = FakeImage()\n fake_im.__class__ = IptcImageFile # type: ignore[assignment]\n iptc_im = cast(IptcImageFile, fake_im)\n\n # parse the IPTC information chunk\n iptc_im.info = {}\n iptc_im.fp = BytesIO(data)\n\n try:\n iptc_im._open()\n except (IndexError, KeyError):\n pass # expected failure\n\n for k, v in iptc_im.info.items():\n if isinstance(k, tuple):\n info[k] = v\n return info\n | .venv\Lib\site-packages\PIL\IptcImagePlugin.py | IptcImagePlugin.py | Python | 6,969 | 0.95 | 0.184 | 0.19598 | vue-tools | 967 | 2025-01-07T10:26:59.732947 | MIT | false | 362112f887bb4906c21278fa4b86674a |
#\n# The Python Imaging Library\n# $Id$\n#\n# JPEG2000 file handling\n#\n# History:\n# 2014-03-12 ajh Created\n# 2021-06-30 rogermb Extract dpi information from the 'resc' header box\n#\n# Copyright (c) 2014 Coriolis Systems Limited\n# Copyright (c) 2014 Alastair Houghton\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport os\nimport struct\nfrom collections.abc import Callable\nfrom typing import IO, cast\n\nfrom . import Image, ImageFile, ImagePalette, _binary\n\n\nclass BoxReader:\n """\n A small helper class to read fields stored in JPEG2000 header boxes\n and to easily step into and read sub-boxes.\n """\n\n def __init__(self, fp: IO[bytes], length: int = -1) -> None:\n self.fp = fp\n self.has_length = length >= 0\n self.length = length\n self.remaining_in_box = -1\n\n def _can_read(self, num_bytes: int) -> bool:\n if self.has_length and self.fp.tell() + num_bytes > self.length:\n # Outside box: ensure we don't read past the known file length\n return False\n if self.remaining_in_box >= 0:\n # Inside box contents: ensure read does not go past box boundaries\n return num_bytes <= self.remaining_in_box\n else:\n return True # No length known, just read\n\n def _read_bytes(self, num_bytes: int) -> bytes:\n if not self._can_read(num_bytes):\n msg = "Not enough data in header"\n raise SyntaxError(msg)\n\n data = self.fp.read(num_bytes)\n if len(data) < num_bytes:\n msg = f"Expected to read {num_bytes} bytes but only got {len(data)}."\n raise OSError(msg)\n\n if self.remaining_in_box > 0:\n self.remaining_in_box -= num_bytes\n return data\n\n def read_fields(self, field_format: str) -> tuple[int | bytes, ...]:\n size = struct.calcsize(field_format)\n data = self._read_bytes(size)\n return struct.unpack(field_format, data)\n\n def read_boxes(self) -> BoxReader:\n size = self.remaining_in_box\n data = self._read_bytes(size)\n return BoxReader(io.BytesIO(data), size)\n\n def has_next_box(self) -> bool:\n if self.has_length:\n return self.fp.tell() + self.remaining_in_box < self.length\n else:\n return True\n\n def next_box_type(self) -> bytes:\n # Skip the rest of the box if it has not been read\n if self.remaining_in_box > 0:\n self.fp.seek(self.remaining_in_box, os.SEEK_CUR)\n self.remaining_in_box = -1\n\n # Read the length and type of the next box\n lbox, tbox = cast(tuple[int, bytes], self.read_fields(">I4s"))\n if lbox == 1:\n lbox = cast(int, self.read_fields(">Q")[0])\n hlen = 16\n else:\n hlen = 8\n\n if lbox < hlen or not self._can_read(lbox - hlen):\n msg = "Invalid header length"\n raise SyntaxError(msg)\n\n self.remaining_in_box = lbox - hlen\n return tbox\n\n\ndef _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]:\n """Parse the JPEG 2000 codestream to extract the size and component\n count from the SIZ marker segment, returning a PIL (size, mode) tuple."""\n\n hdr = fp.read(2)\n lsiz = _binary.i16be(hdr)\n siz = hdr + fp.read(lsiz - 2)\n lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(\n ">HHIIIIIIIIH", siz\n )\n\n size = (xsiz - xosiz, ysiz - yosiz)\n if csiz == 1:\n ssiz = struct.unpack_from(">B", siz, 38)\n if (ssiz[0] & 0x7F) + 1 > 8:\n mode = "I;16"\n else:\n mode = "L"\n elif csiz == 2:\n mode = "LA"\n elif csiz == 3:\n mode = "RGB"\n elif csiz == 4:\n mode = "RGBA"\n else:\n msg = "unable to determine J2K image mode"\n raise SyntaxError(msg)\n\n return size, mode\n\n\ndef _res_to_dpi(num: int, denom: int, exp: int) -> float | None:\n """Convert JPEG2000's (numerator, denominator, exponent-base-10) resolution,\n calculated as (num / denom) * 10^exp and stored in dots per meter,\n to floating-point dots per inch."""\n if denom == 0:\n return None\n return (254 * num * (10**exp)) / (10000 * denom)\n\n\ndef _parse_jp2_header(\n fp: IO[bytes],\n) -> tuple[\n tuple[int, int],\n str,\n str | None,\n tuple[float, float] | None,\n ImagePalette.ImagePalette | None,\n]:\n """Parse the JP2 header box to extract size, component count,\n color space information, and optionally DPI information,\n returning a (size, mode, mimetype, dpi) tuple."""\n\n # Find the JP2 header box\n reader = BoxReader(fp)\n header = None\n mimetype = None\n while reader.has_next_box():\n tbox = reader.next_box_type()\n\n if tbox == b"jp2h":\n header = reader.read_boxes()\n break\n elif tbox == b"ftyp":\n if reader.read_fields(">4s")[0] == b"jpx ":\n mimetype = "image/jpx"\n assert header is not None\n\n size = None\n mode = None\n bpc = None\n nc = None\n dpi = None # 2-tuple of DPI info, or None\n palette = None\n\n while header.has_next_box():\n tbox = header.next_box_type()\n\n if tbox == b"ihdr":\n height, width, nc, bpc = header.read_fields(">IIHB")\n assert isinstance(height, int)\n assert isinstance(width, int)\n assert isinstance(bpc, int)\n size = (width, height)\n if nc == 1 and (bpc & 0x7F) > 8:\n mode = "I;16"\n elif nc == 1:\n mode = "L"\n elif nc == 2:\n mode = "LA"\n elif nc == 3:\n mode = "RGB"\n elif nc == 4:\n mode = "RGBA"\n elif tbox == b"colr" and nc == 4:\n meth, _, _, enumcs = header.read_fields(">BBBI")\n if meth == 1 and enumcs == 12:\n mode = "CMYK"\n elif tbox == b"pclr" and mode in ("L", "LA"):\n ne, npc = header.read_fields(">HB")\n assert isinstance(ne, int)\n assert isinstance(npc, int)\n max_bitdepth = 0\n for bitdepth in header.read_fields(">" + ("B" * npc)):\n assert isinstance(bitdepth, int)\n if bitdepth > max_bitdepth:\n max_bitdepth = bitdepth\n if max_bitdepth <= 8:\n palette = ImagePalette.ImagePalette("RGBA" if npc == 4 else "RGB")\n for i in range(ne):\n color: list[int] = []\n for value in header.read_fields(">" + ("B" * npc)):\n assert isinstance(value, int)\n color.append(value)\n palette.getcolor(tuple(color))\n mode = "P" if mode == "L" else "PA"\n elif tbox == b"res ":\n res = header.read_boxes()\n while res.has_next_box():\n tres = res.next_box_type()\n if tres == b"resc":\n vrcn, vrcd, hrcn, hrcd, vrce, hrce = res.read_fields(">HHHHBB")\n assert isinstance(vrcn, int)\n assert isinstance(vrcd, int)\n assert isinstance(hrcn, int)\n assert isinstance(hrcd, int)\n assert isinstance(vrce, int)\n assert isinstance(hrce, int)\n hres = _res_to_dpi(hrcn, hrcd, hrce)\n vres = _res_to_dpi(vrcn, vrcd, vrce)\n if hres is not None and vres is not None:\n dpi = (hres, vres)\n break\n\n if size is None or mode is None:\n msg = "Malformed JP2 header"\n raise SyntaxError(msg)\n\n return size, mode, mimetype, dpi, palette\n\n\n##\n# Image plugin for JPEG2000 images.\n\n\nclass Jpeg2KImageFile(ImageFile.ImageFile):\n format = "JPEG2000"\n format_description = "JPEG 2000 (ISO 15444)"\n\n def _open(self) -> None:\n sig = self.fp.read(4)\n if sig == b"\xff\x4f\xff\x51":\n self.codec = "j2k"\n self._size, self._mode = _parse_codestream(self.fp)\n self._parse_comment()\n else:\n sig = sig + self.fp.read(8)\n\n if sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a":\n self.codec = "jp2"\n header = _parse_jp2_header(self.fp)\n self._size, self._mode, self.custom_mimetype, dpi, self.palette = header\n if dpi is not None:\n self.info["dpi"] = dpi\n if self.fp.read(12).endswith(b"jp2c\xff\x4f\xff\x51"):\n hdr = self.fp.read(2)\n length = _binary.i16be(hdr)\n self.fp.seek(length - 2, os.SEEK_CUR)\n self._parse_comment()\n else:\n msg = "not a JPEG 2000 file"\n raise SyntaxError(msg)\n\n self._reduce = 0\n self.layers = 0\n\n fd = -1\n length = -1\n\n try:\n fd = self.fp.fileno()\n length = os.fstat(fd).st_size\n except Exception:\n fd = -1\n try:\n pos = self.fp.tell()\n self.fp.seek(0, io.SEEK_END)\n length = self.fp.tell()\n self.fp.seek(pos)\n except Exception:\n length = -1\n\n self.tile = [\n ImageFile._Tile(\n "jpeg2k",\n (0, 0) + self.size,\n 0,\n (self.codec, self._reduce, self.layers, fd, length),\n )\n ]\n\n def _parse_comment(self) -> None:\n while True:\n marker = self.fp.read(2)\n if not marker:\n break\n typ = marker[1]\n if typ in (0x90, 0xD9):\n # Start of tile or end of codestream\n break\n hdr = self.fp.read(2)\n length = _binary.i16be(hdr)\n if typ == 0x64:\n # Comment\n self.info["comment"] = self.fp.read(length - 2)[2:]\n break\n else:\n self.fp.seek(length - 2, os.SEEK_CUR)\n\n @property # type: ignore[override]\n def reduce(\n self,\n ) -> (\n Callable[[int | tuple[int, int], tuple[int, int, int, int] | None], Image.Image]\n | int\n ):\n # https://github.com/python-pillow/Pillow/issues/4343 found that the\n # new Image 'reduce' method was shadowed by this plugin's 'reduce'\n # property. This attempts to allow for both scenarios\n return self._reduce or super().reduce\n\n @reduce.setter\n def reduce(self, value: int) -> None:\n self._reduce = value\n\n def load(self) -> Image.core.PixelAccess | None:\n if self.tile and self._reduce:\n power = 1 << self._reduce\n adjust = power >> 1\n self._size = (\n int((self.size[0] + adjust) / power),\n int((self.size[1] + adjust) / power),\n )\n\n # Update the reduce and layers settings\n t = self.tile[0]\n assert isinstance(t[3], tuple)\n t3 = (t[3][0], self._reduce, self.layers, t[3][3], t[3][4])\n self.tile = [ImageFile._Tile(t[0], (0, 0) + self.size, t[2], t3)]\n\n return ImageFile.ImageFile.load(self)\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(\n (b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a")\n )\n\n\n# ------------------------------------------------------------\n# Save support\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n # Get the keyword arguments\n info = im.encoderinfo\n\n if isinstance(filename, str):\n filename = filename.encode()\n if filename.endswith(b".j2k") or info.get("no_jp2", False):\n kind = "j2k"\n else:\n kind = "jp2"\n\n offset = info.get("offset", None)\n tile_offset = info.get("tile_offset", None)\n tile_size = info.get("tile_size", None)\n quality_mode = info.get("quality_mode", "rates")\n quality_layers = info.get("quality_layers", None)\n if quality_layers is not None and not (\n isinstance(quality_layers, (list, tuple))\n and all(\n isinstance(quality_layer, (int, float)) for quality_layer in quality_layers\n )\n ):\n msg = "quality_layers must be a sequence of numbers"\n raise ValueError(msg)\n\n num_resolutions = info.get("num_resolutions", 0)\n cblk_size = info.get("codeblock_size", None)\n precinct_size = info.get("precinct_size", None)\n irreversible = info.get("irreversible", False)\n progression = info.get("progression", "LRCP")\n cinema_mode = info.get("cinema_mode", "no")\n mct = info.get("mct", 0)\n signed = info.get("signed", False)\n comment = info.get("comment")\n if isinstance(comment, str):\n comment = comment.encode()\n plt = info.get("plt", False)\n\n fd = -1\n if hasattr(fp, "fileno"):\n try:\n fd = fp.fileno()\n except Exception:\n fd = -1\n\n im.encoderconfig = (\n offset,\n tile_offset,\n tile_size,\n quality_mode,\n quality_layers,\n num_resolutions,\n cblk_size,\n precinct_size,\n irreversible,\n progression,\n cinema_mode,\n mct,\n signed,\n fd,\n comment,\n plt,\n )\n\n ImageFile._save(im, fp, [ImageFile._Tile("jpeg2k", (0, 0) + im.size, 0, kind)])\n\n\n# ------------------------------------------------------------\n# Registry stuff\n\n\nImage.register_open(Jpeg2KImageFile.format, Jpeg2KImageFile, _accept)\nImage.register_save(Jpeg2KImageFile.format, _save)\n\nImage.register_extensions(\n Jpeg2KImageFile.format, [".jp2", ".j2k", ".jpc", ".jpf", ".jpx", ".j2c"]\n)\n\nImage.register_mime(Jpeg2KImageFile.format, "image/jp2")\n | .venv\Lib\site-packages\PIL\Jpeg2KImagePlugin.py | Jpeg2KImagePlugin.py | Python | 14,307 | 0.95 | 0.162896 | 0.087766 | node-utils | 866 | 2024-11-29T04:20:37.744915 | BSD-3-Clause | false | dfcdf6ed285bc02cdf7c089771d272ce |
#\n# The Python Imaging Library.\n# $Id$\n#\n# JPEG (JFIF) file handling\n#\n# See "Digital Compression and Coding of Continuous-Tone Still Images,\n# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)\n#\n# History:\n# 1995-09-09 fl Created\n# 1995-09-13 fl Added full parser\n# 1996-03-25 fl Added hack to use the IJG command line utilities\n# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug\n# 1996-05-28 fl Added draft support, JFIF version (0.1)\n# 1996-12-30 fl Added encoder options, added progression property (0.2)\n# 1997-08-27 fl Save mode 1 images as BW (0.3)\n# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)\n# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)\n# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)\n# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)\n# 2003-04-25 fl Added experimental EXIF decoder (0.5)\n# 2003-06-06 fl Added experimental EXIF GPSinfo decoder\n# 2003-09-13 fl Extract COM markers\n# 2009-09-06 fl Added icc_profile support (from Florian Hoech)\n# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)\n# 2009-03-08 fl Added subsampling support (from Justin Huff).\n#\n# Copyright (c) 1997-2003 by Secret Labs AB.\n# Copyright (c) 1995-1996 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport array\nimport io\nimport math\nimport os\nimport struct\nimport subprocess\nimport sys\nimport tempfile\nimport warnings\nfrom typing import IO, Any\n\nfrom . import Image, ImageFile\nfrom ._binary import i16be as i16\nfrom ._binary import i32be as i32\nfrom ._binary import o8\nfrom ._binary import o16be as o16\nfrom ._deprecate import deprecate\nfrom .JpegPresets import presets\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from .MpoImagePlugin import MpoImageFile\n\n#\n# Parser\n\n\ndef Skip(self: JpegImageFile, marker: int) -> None:\n n = i16(self.fp.read(2)) - 2\n ImageFile._safe_read(self.fp, n)\n\n\ndef APP(self: JpegImageFile, marker: int) -> None:\n #\n # Application marker. Store these in the APP dictionary.\n # Also look for well-known application markers.\n\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n\n app = f"APP{marker & 15}"\n\n self.app[app] = s # compatibility\n self.applist.append((app, s))\n\n if marker == 0xFFE0 and s.startswith(b"JFIF"):\n # extract JFIF information\n self.info["jfif"] = version = i16(s, 5) # version\n self.info["jfif_version"] = divmod(version, 256)\n # extract JFIF properties\n try:\n jfif_unit = s[7]\n jfif_density = i16(s, 8), i16(s, 10)\n except Exception:\n pass\n else:\n if jfif_unit == 1:\n self.info["dpi"] = jfif_density\n elif jfif_unit == 2: # cm\n # 1 dpcm = 2.54 dpi\n self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)\n self.info["jfif_unit"] = jfif_unit\n self.info["jfif_density"] = jfif_density\n elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):\n # extract EXIF information\n if "exif" in self.info:\n self.info["exif"] += s[6:]\n else:\n self.info["exif"] = s\n self._exif_offset = self.fp.tell() - n + 6\n elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):\n self.info["xmp"] = s.split(b"\x00", 1)[1]\n elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):\n # extract FlashPix information (incomplete)\n self.info["flashpix"] = s # FIXME: value will change\n elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):\n # Since an ICC profile can be larger than the maximum size of\n # a JPEG marker (64K), we need provisions to split it into\n # multiple markers. The format defined by the ICC specifies\n # one or more APP2 markers containing the following data:\n # Identifying string ASCII "ICC_PROFILE\0" (12 bytes)\n # Marker sequence number 1, 2, etc (1 byte)\n # Number of markers Total of APP2's used (1 byte)\n # Profile data (remainder of APP2 data)\n # Decoders should use the marker sequence numbers to\n # reassemble the profile, rather than assuming that the APP2\n # markers appear in the correct sequence.\n self.icclist.append(s)\n elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):\n # parse the image resource block\n offset = 14\n photoshop = self.info.setdefault("photoshop", {})\n while s[offset : offset + 4] == b"8BIM":\n try:\n offset += 4\n # resource code\n code = i16(s, offset)\n offset += 2\n # resource name (usually empty)\n name_len = s[offset]\n # name = s[offset+1:offset+1+name_len]\n offset += 1 + name_len\n offset += offset & 1 # align\n # resource data block\n size = i32(s, offset)\n offset += 4\n data = s[offset : offset + size]\n if code == 0x03ED: # ResolutionInfo\n photoshop[code] = {\n "XResolution": i32(data, 0) / 65536,\n "DisplayedUnitsX": i16(data, 4),\n "YResolution": i32(data, 8) / 65536,\n "DisplayedUnitsY": i16(data, 12),\n }\n else:\n photoshop[code] = data\n offset += size\n offset += offset & 1 # align\n except struct.error:\n break # insufficient data\n\n elif marker == 0xFFEE and s.startswith(b"Adobe"):\n self.info["adobe"] = i16(s, 5)\n # extract Adobe custom properties\n try:\n adobe_transform = s[11]\n except IndexError:\n pass\n else:\n self.info["adobe_transform"] = adobe_transform\n elif marker == 0xFFE2 and s.startswith(b"MPF\0"):\n # extract MPO information\n self.info["mp"] = s[4:]\n # offset is current location minus buffer size\n # plus constant header size\n self.info["mpoffset"] = self.fp.tell() - n + 4\n\n\ndef COM(self: JpegImageFile, marker: int) -> None:\n #\n # Comment marker. Store these in the APP dictionary.\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n\n self.info["comment"] = s\n self.app["COM"] = s # compatibility\n self.applist.append(("COM", s))\n\n\ndef SOF(self: JpegImageFile, marker: int) -> None:\n #\n # Start of frame marker. Defines the size and mode of the\n # image. JPEG is colour blind, so we use some simple\n # heuristics to map the number of layers to an appropriate\n # mode. Note that this could be made a bit brighter, by\n # looking for JFIF and Adobe APP markers.\n\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n self._size = i16(s, 3), i16(s, 1)\n\n self.bits = s[0]\n if self.bits != 8:\n msg = f"cannot handle {self.bits}-bit layers"\n raise SyntaxError(msg)\n\n self.layers = s[5]\n if self.layers == 1:\n self._mode = "L"\n elif self.layers == 3:\n self._mode = "RGB"\n elif self.layers == 4:\n self._mode = "CMYK"\n else:\n msg = f"cannot handle {self.layers}-layer images"\n raise SyntaxError(msg)\n\n if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:\n self.info["progressive"] = self.info["progression"] = 1\n\n if self.icclist:\n # fixup icc profile\n self.icclist.sort() # sort by sequence number\n if self.icclist[0][13] == len(self.icclist):\n profile = [p[14:] for p in self.icclist]\n icc_profile = b"".join(profile)\n else:\n icc_profile = None # wrong number of fragments\n self.info["icc_profile"] = icc_profile\n self.icclist = []\n\n for i in range(6, len(s), 3):\n t = s[i : i + 3]\n # 4-tuples: id, vsamp, hsamp, qtable\n self.layer.append((t[0], t[1] // 16, t[1] & 15, t[2]))\n\n\ndef DQT(self: JpegImageFile, marker: int) -> None:\n #\n # Define quantization table. Note that there might be more\n # than one table in each marker.\n\n # FIXME: The quantization tables can be used to estimate the\n # compression quality.\n\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n while len(s):\n v = s[0]\n precision = 1 if (v // 16 == 0) else 2 # in bytes\n qt_length = 1 + precision * 64\n if len(s) < qt_length:\n msg = "bad quantization table marker"\n raise SyntaxError(msg)\n data = array.array("B" if precision == 1 else "H", s[1:qt_length])\n if sys.byteorder == "little" and precision > 1:\n data.byteswap() # the values are always big-endian\n self.quantization[v & 15] = [data[i] for i in zigzag_index]\n s = s[qt_length:]\n\n\n#\n# JPEG marker table\n\nMARKER = {\n 0xFFC0: ("SOF0", "Baseline DCT", SOF),\n 0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),\n 0xFFC2: ("SOF2", "Progressive DCT", SOF),\n 0xFFC3: ("SOF3", "Spatial lossless", SOF),\n 0xFFC4: ("DHT", "Define Huffman table", Skip),\n 0xFFC5: ("SOF5", "Differential sequential DCT", SOF),\n 0xFFC6: ("SOF6", "Differential progressive DCT", SOF),\n 0xFFC7: ("SOF7", "Differential spatial", SOF),\n 0xFFC8: ("JPG", "Extension", None),\n 0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),\n 0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),\n 0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),\n 0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),\n 0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),\n 0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),\n 0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),\n 0xFFD0: ("RST0", "Restart 0", None),\n 0xFFD1: ("RST1", "Restart 1", None),\n 0xFFD2: ("RST2", "Restart 2", None),\n 0xFFD3: ("RST3", "Restart 3", None),\n 0xFFD4: ("RST4", "Restart 4", None),\n 0xFFD5: ("RST5", "Restart 5", None),\n 0xFFD6: ("RST6", "Restart 6", None),\n 0xFFD7: ("RST7", "Restart 7", None),\n 0xFFD8: ("SOI", "Start of image", None),\n 0xFFD9: ("EOI", "End of image", None),\n 0xFFDA: ("SOS", "Start of scan", Skip),\n 0xFFDB: ("DQT", "Define quantization table", DQT),\n 0xFFDC: ("DNL", "Define number of lines", Skip),\n 0xFFDD: ("DRI", "Define restart interval", Skip),\n 0xFFDE: ("DHP", "Define hierarchical progression", SOF),\n 0xFFDF: ("EXP", "Expand reference component", Skip),\n 0xFFE0: ("APP0", "Application segment 0", APP),\n 0xFFE1: ("APP1", "Application segment 1", APP),\n 0xFFE2: ("APP2", "Application segment 2", APP),\n 0xFFE3: ("APP3", "Application segment 3", APP),\n 0xFFE4: ("APP4", "Application segment 4", APP),\n 0xFFE5: ("APP5", "Application segment 5", APP),\n 0xFFE6: ("APP6", "Application segment 6", APP),\n 0xFFE7: ("APP7", "Application segment 7", APP),\n 0xFFE8: ("APP8", "Application segment 8", APP),\n 0xFFE9: ("APP9", "Application segment 9", APP),\n 0xFFEA: ("APP10", "Application segment 10", APP),\n 0xFFEB: ("APP11", "Application segment 11", APP),\n 0xFFEC: ("APP12", "Application segment 12", APP),\n 0xFFED: ("APP13", "Application segment 13", APP),\n 0xFFEE: ("APP14", "Application segment 14", APP),\n 0xFFEF: ("APP15", "Application segment 15", APP),\n 0xFFF0: ("JPG0", "Extension 0", None),\n 0xFFF1: ("JPG1", "Extension 1", None),\n 0xFFF2: ("JPG2", "Extension 2", None),\n 0xFFF3: ("JPG3", "Extension 3", None),\n 0xFFF4: ("JPG4", "Extension 4", None),\n 0xFFF5: ("JPG5", "Extension 5", None),\n 0xFFF6: ("JPG6", "Extension 6", None),\n 0xFFF7: ("JPG7", "Extension 7", None),\n 0xFFF8: ("JPG8", "Extension 8", None),\n 0xFFF9: ("JPG9", "Extension 9", None),\n 0xFFFA: ("JPG10", "Extension 10", None),\n 0xFFFB: ("JPG11", "Extension 11", None),\n 0xFFFC: ("JPG12", "Extension 12", None),\n 0xFFFD: ("JPG13", "Extension 13", None),\n 0xFFFE: ("COM", "Comment", COM),\n}\n\n\ndef _accept(prefix: bytes) -> bool:\n # Magic number was taken from https://en.wikipedia.org/wiki/JPEG\n return prefix.startswith(b"\xff\xd8\xff")\n\n\n##\n# Image plugin for JPEG and JFIF images.\n\n\nclass JpegImageFile(ImageFile.ImageFile):\n format = "JPEG"\n format_description = "JPEG (ISO 10918)"\n\n def _open(self) -> None:\n s = self.fp.read(3)\n\n if not _accept(s):\n msg = "not a JPEG file"\n raise SyntaxError(msg)\n s = b"\xff"\n\n # Create attributes\n self.bits = self.layers = 0\n self._exif_offset = 0\n\n # JPEG specifics (internal)\n self.layer: list[tuple[int, int, int, int]] = []\n self._huffman_dc: dict[Any, Any] = {}\n self._huffman_ac: dict[Any, Any] = {}\n self.quantization: dict[int, list[int]] = {}\n self.app: dict[str, bytes] = {} # compatibility\n self.applist: list[tuple[str, bytes]] = []\n self.icclist: list[bytes] = []\n\n while True:\n i = s[0]\n if i == 0xFF:\n s = s + self.fp.read(1)\n i = i16(s)\n else:\n # Skip non-0xFF junk\n s = self.fp.read(1)\n continue\n\n if i in MARKER:\n name, description, handler = MARKER[i]\n if handler is not None:\n handler(self, i)\n if i == 0xFFDA: # start of scan\n rawmode = self.mode\n if self.mode == "CMYK":\n rawmode = "CMYK;I" # assume adobe conventions\n self.tile = [\n ImageFile._Tile("jpeg", (0, 0) + self.size, 0, (rawmode, ""))\n ]\n # self.__offset = self.fp.tell()\n break\n s = self.fp.read(1)\n elif i in {0, 0xFFFF}:\n # padded marker or junk; move on\n s = b"\xff"\n elif i == 0xFF00: # Skip extraneous data (escaped 0xFF)\n s = self.fp.read(1)\n else:\n msg = "no marker found"\n raise SyntaxError(msg)\n\n self._read_dpi_from_exif()\n\n def __getattr__(self, name: str) -> Any:\n if name in ("huffman_ac", "huffman_dc"):\n deprecate(name, 12)\n return getattr(self, "_" + name)\n raise AttributeError(name)\n\n def __getstate__(self) -> list[Any]:\n return super().__getstate__() + [self.layers, self.layer]\n\n def __setstate__(self, state: list[Any]) -> None:\n self.layers, self.layer = state[6:]\n super().__setstate__(state)\n\n def load_read(self, read_bytes: int) -> bytes:\n """\n internal: read more image data\n For premature EOF and LOAD_TRUNCATED_IMAGES adds EOI marker\n so libjpeg can finish decoding\n """\n s = self.fp.read(read_bytes)\n\n if not s and ImageFile.LOAD_TRUNCATED_IMAGES and not hasattr(self, "_ended"):\n # Premature EOF.\n # Pretend file is finished adding EOI marker\n self._ended = True\n return b"\xff\xd9"\n\n return s\n\n def draft(\n self, mode: str | None, size: tuple[int, int] | None\n ) -> tuple[str, tuple[int, int, float, float]] | None:\n if len(self.tile) != 1:\n return None\n\n # Protect from second call\n if self.decoderconfig:\n return None\n\n d, e, o, a = self.tile[0]\n scale = 1\n original_size = self.size\n\n assert isinstance(a, tuple)\n if a[0] == "RGB" and mode in ["L", "YCbCr"]:\n self._mode = mode\n a = mode, ""\n\n if size:\n scale = min(self.size[0] // size[0], self.size[1] // size[1])\n for s in [8, 4, 2, 1]:\n if scale >= s:\n break\n assert e is not None\n e = (\n e[0],\n e[1],\n (e[2] - e[0] + s - 1) // s + e[0],\n (e[3] - e[1] + s - 1) // s + e[1],\n )\n self._size = ((self.size[0] + s - 1) // s, (self.size[1] + s - 1) // s)\n scale = s\n\n self.tile = [ImageFile._Tile(d, e, o, a)]\n self.decoderconfig = (scale, 0)\n\n box = (0, 0, original_size[0] / scale, original_size[1] / scale)\n return self.mode, box\n\n def load_djpeg(self) -> None:\n # ALTERNATIVE: handle JPEGs via the IJG command line utilities\n\n f, path = tempfile.mkstemp()\n os.close(f)\n if os.path.exists(self.filename):\n subprocess.check_call(["djpeg", "-outfile", path, self.filename])\n else:\n try:\n os.unlink(path)\n except OSError:\n pass\n\n msg = "Invalid Filename"\n raise ValueError(msg)\n\n try:\n with Image.open(path) as _im:\n _im.load()\n self.im = _im.im\n finally:\n try:\n os.unlink(path)\n except OSError:\n pass\n\n self._mode = self.im.mode\n self._size = self.im.size\n\n self.tile = []\n\n def _getexif(self) -> dict[int, Any] | None:\n return _getexif(self)\n\n def _read_dpi_from_exif(self) -> None:\n # If DPI isn't in JPEG header, fetch from EXIF\n if "dpi" in self.info or "exif" not in self.info:\n return\n try:\n exif = self.getexif()\n resolution_unit = exif[0x0128]\n x_resolution = exif[0x011A]\n try:\n dpi = float(x_resolution[0]) / x_resolution[1]\n except TypeError:\n dpi = x_resolution\n if math.isnan(dpi):\n msg = "DPI is not a number"\n raise ValueError(msg)\n if resolution_unit == 3: # cm\n # 1 dpcm = 2.54 dpi\n dpi *= 2.54\n self.info["dpi"] = dpi, dpi\n except (\n struct.error, # truncated EXIF\n KeyError, # dpi not included\n SyntaxError, # invalid/unreadable EXIF\n TypeError, # dpi is an invalid float\n ValueError, # dpi is an invalid float\n ZeroDivisionError, # invalid dpi rational value\n ):\n self.info["dpi"] = 72, 72\n\n def _getmp(self) -> dict[int, Any] | None:\n return _getmp(self)\n\n\ndef _getexif(self: JpegImageFile) -> dict[int, Any] | None:\n if "exif" not in self.info:\n return None\n return self.getexif()._get_merged_dict()\n\n\ndef _getmp(self: JpegImageFile) -> dict[int, Any] | None:\n # Extract MP information. This method was inspired by the "highly\n # experimental" _getexif version that's been in use for years now,\n # itself based on the ImageFileDirectory class in the TIFF plugin.\n\n # The MP record essentially consists of a TIFF file embedded in a JPEG\n # application marker.\n try:\n data = self.info["mp"]\n except KeyError:\n return None\n file_contents = io.BytesIO(data)\n head = file_contents.read(8)\n endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"\n # process dictionary\n from . import TiffImagePlugin\n\n try:\n info = TiffImagePlugin.ImageFileDirectory_v2(head)\n file_contents.seek(info.next)\n info.load(file_contents)\n mp = dict(info)\n except Exception as e:\n msg = "malformed MP Index (unreadable directory)"\n raise SyntaxError(msg) from e\n # it's an error not to have a number of images\n try:\n quant = mp[0xB001]\n except KeyError as e:\n msg = "malformed MP Index (no number of images)"\n raise SyntaxError(msg) from e\n # get MP entries\n mpentries = []\n try:\n rawmpentries = mp[0xB002]\n for entrynum in range(quant):\n unpackedentry = struct.unpack_from(\n f"{endianness}LLLHH", rawmpentries, entrynum * 16\n )\n labels = ("Attribute", "Size", "DataOffset", "EntryNo1", "EntryNo2")\n mpentry = dict(zip(labels, unpackedentry))\n mpentryattr = {\n "DependentParentImageFlag": bool(mpentry["Attribute"] & (1 << 31)),\n "DependentChildImageFlag": bool(mpentry["Attribute"] & (1 << 30)),\n "RepresentativeImageFlag": bool(mpentry["Attribute"] & (1 << 29)),\n "Reserved": (mpentry["Attribute"] & (3 << 27)) >> 27,\n "ImageDataFormat": (mpentry["Attribute"] & (7 << 24)) >> 24,\n "MPType": mpentry["Attribute"] & 0x00FFFFFF,\n }\n if mpentryattr["ImageDataFormat"] == 0:\n mpentryattr["ImageDataFormat"] = "JPEG"\n else:\n msg = "unsupported picture format in MPO"\n raise SyntaxError(msg)\n mptypemap = {\n 0x000000: "Undefined",\n 0x010001: "Large Thumbnail (VGA Equivalent)",\n 0x010002: "Large Thumbnail (Full HD Equivalent)",\n 0x020001: "Multi-Frame Image (Panorama)",\n 0x020002: "Multi-Frame Image: (Disparity)",\n 0x020003: "Multi-Frame Image: (Multi-Angle)",\n 0x030000: "Baseline MP Primary Image",\n }\n mpentryattr["MPType"] = mptypemap.get(mpentryattr["MPType"], "Unknown")\n mpentry["Attribute"] = mpentryattr\n mpentries.append(mpentry)\n mp[0xB002] = mpentries\n except KeyError as e:\n msg = "malformed MP Index (bad MP Entry)"\n raise SyntaxError(msg) from e\n # Next we should try and parse the individual image unique ID list;\n # we don't because I've never seen this actually used in a real MPO\n # file and so can't test it.\n return mp\n\n\n# --------------------------------------------------------------------\n# stuff to save JPEG files\n\nRAWMODE = {\n "1": "L",\n "L": "L",\n "RGB": "RGB",\n "RGBX": "RGB",\n "CMYK": "CMYK;I", # assume adobe conventions\n "YCbCr": "YCbCr",\n}\n\n# fmt: off\nzigzag_index = (\n 0, 1, 5, 6, 14, 15, 27, 28,\n 2, 4, 7, 13, 16, 26, 29, 42,\n 3, 8, 12, 17, 25, 30, 41, 43,\n 9, 11, 18, 24, 31, 40, 44, 53,\n 10, 19, 23, 32, 39, 45, 52, 54,\n 20, 22, 33, 38, 46, 51, 55, 60,\n 21, 34, 37, 47, 50, 56, 59, 61,\n 35, 36, 48, 49, 57, 58, 62, 63,\n)\n\nsamplings = {\n (1, 1, 1, 1, 1, 1): 0,\n (2, 1, 1, 1, 1, 1): 1,\n (2, 2, 1, 1, 1, 1): 2,\n}\n# fmt: on\n\n\ndef get_sampling(im: Image.Image) -> int:\n # There's no subsampling when images have only 1 layer\n # (grayscale images) or when they are CMYK (4 layers),\n # so set subsampling to the default value.\n #\n # NOTE: currently Pillow can't encode JPEG to YCCK format.\n # If YCCK support is added in the future, subsampling code will have\n # to be updated (here and in JpegEncode.c) to deal with 4 layers.\n if not isinstance(im, JpegImageFile) or im.layers in (1, 4):\n return -1\n sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]\n return samplings.get(sampling, -1)\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.width == 0 or im.height == 0:\n msg = "cannot write empty image as JPEG"\n raise ValueError(msg)\n\n try:\n rawmode = RAWMODE[im.mode]\n except KeyError as e:\n msg = f"cannot write mode {im.mode} as JPEG"\n raise OSError(msg) from e\n\n info = im.encoderinfo\n\n dpi = [round(x) for x in info.get("dpi", (0, 0))]\n\n quality = info.get("quality", -1)\n subsampling = info.get("subsampling", -1)\n qtables = info.get("qtables")\n\n if quality == "keep":\n quality = -1\n subsampling = "keep"\n qtables = "keep"\n elif quality in presets:\n preset = presets[quality]\n quality = -1\n subsampling = preset.get("subsampling", -1)\n qtables = preset.get("quantization")\n elif not isinstance(quality, int):\n msg = "Invalid quality setting"\n raise ValueError(msg)\n else:\n if subsampling in presets:\n subsampling = presets[subsampling].get("subsampling", -1)\n if isinstance(qtables, str) and qtables in presets:\n qtables = presets[qtables].get("quantization")\n\n if subsampling == "4:4:4":\n subsampling = 0\n elif subsampling == "4:2:2":\n subsampling = 1\n elif subsampling == "4:2:0":\n subsampling = 2\n elif subsampling == "4:1:1":\n # For compatibility. Before Pillow 4.3, 4:1:1 actually meant 4:2:0.\n # Set 4:2:0 if someone is still using that value.\n subsampling = 2\n elif subsampling == "keep":\n if im.format != "JPEG":\n msg = "Cannot use 'keep' when original image is not a JPEG"\n raise ValueError(msg)\n subsampling = get_sampling(im)\n\n def validate_qtables(\n qtables: (\n str | tuple[list[int], ...] | list[list[int]] | dict[int, list[int]] | None\n ),\n ) -> list[list[int]] | None:\n if qtables is None:\n return qtables\n if isinstance(qtables, str):\n try:\n lines = [\n int(num)\n for line in qtables.splitlines()\n for num in line.split("#", 1)[0].split()\n ]\n except ValueError as e:\n msg = "Invalid quantization table"\n raise ValueError(msg) from e\n else:\n qtables = [lines[s : s + 64] for s in range(0, len(lines), 64)]\n if isinstance(qtables, (tuple, list, dict)):\n if isinstance(qtables, dict):\n qtables = [\n qtables[key] for key in range(len(qtables)) if key in qtables\n ]\n elif isinstance(qtables, tuple):\n qtables = list(qtables)\n if not (0 < len(qtables) < 5):\n msg = "None or too many quantization tables"\n raise ValueError(msg)\n for idx, table in enumerate(qtables):\n try:\n if len(table) != 64:\n msg = "Invalid quantization table"\n raise TypeError(msg)\n table_array = array.array("H", table)\n except TypeError as e:\n msg = "Invalid quantization table"\n raise ValueError(msg) from e\n else:\n qtables[idx] = list(table_array)\n return qtables\n\n if qtables == "keep":\n if im.format != "JPEG":\n msg = "Cannot use 'keep' when original image is not a JPEG"\n raise ValueError(msg)\n qtables = getattr(im, "quantization", None)\n qtables = validate_qtables(qtables)\n\n extra = info.get("extra", b"")\n\n MAX_BYTES_IN_MARKER = 65533\n if xmp := info.get("xmp"):\n overhead_len = 29 # b"http://ns.adobe.com/xap/1.0/\x00"\n max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len\n if len(xmp) > max_data_bytes_in_marker:\n msg = "XMP data is too long"\n raise ValueError(msg)\n size = o16(2 + overhead_len + len(xmp))\n extra += b"\xff\xe1" + size + b"http://ns.adobe.com/xap/1.0/\x00" + xmp\n\n if icc_profile := info.get("icc_profile"):\n overhead_len = 14 # b"ICC_PROFILE\0" + o8(i) + o8(len(markers))\n max_data_bytes_in_marker = MAX_BYTES_IN_MARKER - overhead_len\n markers = []\n while icc_profile:\n markers.append(icc_profile[:max_data_bytes_in_marker])\n icc_profile = icc_profile[max_data_bytes_in_marker:]\n i = 1\n for marker in markers:\n size = o16(2 + overhead_len + len(marker))\n extra += (\n b"\xff\xe2"\n + size\n + b"ICC_PROFILE\0"\n + o8(i)\n + o8(len(markers))\n + marker\n )\n i += 1\n\n comment = info.get("comment", im.info.get("comment"))\n\n # "progressive" is the official name, but older documentation\n # says "progression"\n # FIXME: issue a warning if the wrong form is used (post-1.1.7)\n progressive = info.get("progressive", False) or info.get("progression", False)\n\n optimize = info.get("optimize", False)\n\n exif = info.get("exif", b"")\n if isinstance(exif, Image.Exif):\n exif = exif.tobytes()\n if len(exif) > MAX_BYTES_IN_MARKER:\n msg = "EXIF data is too long"\n raise ValueError(msg)\n\n # get keyword arguments\n im.encoderconfig = (\n quality,\n progressive,\n info.get("smooth", 0),\n optimize,\n info.get("keep_rgb", False),\n info.get("streamtype", 0),\n dpi,\n subsampling,\n info.get("restart_marker_blocks", 0),\n info.get("restart_marker_rows", 0),\n qtables,\n comment,\n extra,\n exif,\n )\n\n # if we optimize, libjpeg needs a buffer big enough to hold the whole image\n # in a shot. Guessing on the size, at im.size bytes. (raw pixel size is\n # channels*size, this is a value that's been used in a django patch.\n # https://github.com/matthewwithanm/django-imagekit/issues/50\n if optimize or progressive:\n # CMYK can be bigger\n if im.mode == "CMYK":\n bufsize = 4 * im.size[0] * im.size[1]\n # keep sets quality to -1, but the actual value may be high.\n elif quality >= 95 or quality == -1:\n bufsize = 2 * im.size[0] * im.size[1]\n else:\n bufsize = im.size[0] * im.size[1]\n if exif:\n bufsize += len(exif) + 5\n if extra:\n bufsize += len(extra) + 1\n else:\n # The EXIF info needs to be written as one block, + APP1, + one spare byte.\n # Ensure that our buffer is big enough. Same with the icc_profile block.\n bufsize = max(len(exif) + 5, len(extra) + 1)\n\n ImageFile._save(\n im, fp, [ImageFile._Tile("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize\n )\n\n\ndef _save_cjpeg(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n # ALTERNATIVE: handle JPEGs via the IJG command line utilities.\n tempfile = im._dump()\n subprocess.check_call(["cjpeg", "-outfile", filename, tempfile])\n try:\n os.unlink(tempfile)\n except OSError:\n pass\n\n\n##\n# Factory for making JPEG and MPO instances\ndef jpeg_factory(\n fp: IO[bytes], filename: str | bytes | None = None\n) -> JpegImageFile | MpoImageFile:\n im = JpegImageFile(fp, filename)\n try:\n mpheader = im._getmp()\n if mpheader is not None and mpheader[45057] > 1:\n for segment, content in im.applist:\n if segment == "APP1" and b' hdrgm:Version="' in content:\n # Ultra HDR images are not yet supported\n return im\n # It's actually an MPO\n from .MpoImagePlugin import MpoImageFile\n\n # Don't reload everything, just convert it.\n im = MpoImageFile.adopt(im, mpheader)\n except (TypeError, IndexError):\n # It is really a JPEG\n pass\n except SyntaxError:\n warnings.warn(\n "Image appears to be a malformed MPO file, it will be "\n "interpreted as a base JPEG file"\n )\n return im\n\n\n# ---------------------------------------------------------------------\n# Registry stuff\n\nImage.register_open(JpegImageFile.format, jpeg_factory, _accept)\nImage.register_save(JpegImageFile.format, _save)\n\nImage.register_extensions(JpegImageFile.format, [".jfif", ".jpe", ".jpg", ".jpeg"])\n\nImage.register_mime(JpegImageFile.format, "image/jpeg")\n | .venv\Lib\site-packages\PIL\JpegImagePlugin.py | JpegImagePlugin.py | Python | 32,688 | 0.95 | 0.145233 | 0.175284 | react-lib | 645 | 2024-01-22T03:12:53.486279 | GPL-3.0 | false | 42949a1a5380fc5472fd82f9ce2e3503 |
"""\nJPEG quality settings equivalent to the Photoshop settings.\nCan be used when saving JPEG files.\n\nThe following presets are available by default:\n``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,\n``low``, ``medium``, ``high``, ``maximum``.\nMore presets can be added to the :py:data:`presets` dict if needed.\n\nTo apply the preset, specify::\n\n quality="preset_name"\n\nTo apply only the quantization table::\n\n qtables="preset_name"\n\nTo apply only the subsampling setting::\n\n subsampling="preset_name"\n\nExample::\n\n im.save("image_name.jpg", quality="web_high")\n\nSubsampling\n-----------\n\nSubsampling is the practice of encoding images by implementing less resolution\nfor chroma information than for luma information.\n(ref.: https://en.wikipedia.org/wiki/Chroma_subsampling)\n\nPossible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2 and\n4:2:0.\n\nYou can get the subsampling of a JPEG with the\n:func:`.JpegImagePlugin.get_sampling` function.\n\nIn JPEG compressed data a JPEG marker is used instead of an EXIF tag.\n(ref.: https://exiv2.org/tags.html)\n\n\nQuantization tables\n-------------------\n\nThey are values use by the DCT (Discrete cosine transform) to remove\n*unnecessary* information from the image (the lossy part of the compression).\n(ref.: https://en.wikipedia.org/wiki/Quantization_matrix#Quantization_matrices,\nhttps://en.wikipedia.org/wiki/JPEG#Quantization)\n\nYou can get the quantization tables of a JPEG with::\n\n im.quantization\n\nThis will return a dict with a number of lists. You can pass this dict\ndirectly as the qtables argument when saving a JPEG.\n\nThe quantization table format in presets is a list with sublists. These formats\nare interchangeable.\n\nLibjpeg ref.:\nhttps://web.archive.org/web/20120328125543/http://www.jpegcameras.com/libjpeg/libjpeg-3.html\n\n"""\n\nfrom __future__ import annotations\n\n# fmt: off\npresets = {\n 'web_low': {'subsampling': 2, # "4:2:0"\n 'quantization': [\n [20, 16, 25, 39, 50, 46, 62, 68,\n 16, 18, 23, 38, 38, 53, 65, 68,\n 25, 23, 31, 38, 53, 65, 68, 68,\n 39, 38, 38, 53, 65, 68, 68, 68,\n 50, 38, 53, 65, 68, 68, 68, 68,\n 46, 53, 65, 68, 68, 68, 68, 68,\n 62, 65, 68, 68, 68, 68, 68, 68,\n 68, 68, 68, 68, 68, 68, 68, 68],\n [21, 25, 32, 38, 54, 68, 68, 68,\n 25, 28, 24, 38, 54, 68, 68, 68,\n 32, 24, 32, 43, 66, 68, 68, 68,\n 38, 38, 43, 53, 68, 68, 68, 68,\n 54, 54, 66, 68, 68, 68, 68, 68,\n 68, 68, 68, 68, 68, 68, 68, 68,\n 68, 68, 68, 68, 68, 68, 68, 68,\n 68, 68, 68, 68, 68, 68, 68, 68]\n ]},\n 'web_medium': {'subsampling': 2, # "4:2:0"\n 'quantization': [\n [16, 11, 11, 16, 23, 27, 31, 30,\n 11, 12, 12, 15, 20, 23, 23, 30,\n 11, 12, 13, 16, 23, 26, 35, 47,\n 16, 15, 16, 23, 26, 37, 47, 64,\n 23, 20, 23, 26, 39, 51, 64, 64,\n 27, 23, 26, 37, 51, 64, 64, 64,\n 31, 23, 35, 47, 64, 64, 64, 64,\n 30, 30, 47, 64, 64, 64, 64, 64],\n [17, 15, 17, 21, 20, 26, 38, 48,\n 15, 19, 18, 17, 20, 26, 35, 43,\n 17, 18, 20, 22, 26, 30, 46, 53,\n 21, 17, 22, 28, 30, 39, 53, 64,\n 20, 20, 26, 30, 39, 48, 64, 64,\n 26, 26, 30, 39, 48, 63, 64, 64,\n 38, 35, 46, 53, 64, 64, 64, 64,\n 48, 43, 53, 64, 64, 64, 64, 64]\n ]},\n 'web_high': {'subsampling': 0, # "4:4:4"\n 'quantization': [\n [6, 4, 4, 6, 9, 11, 12, 16,\n 4, 5, 5, 6, 8, 10, 12, 12,\n 4, 5, 5, 6, 10, 12, 14, 19,\n 6, 6, 6, 11, 12, 15, 19, 28,\n 9, 8, 10, 12, 16, 20, 27, 31,\n 11, 10, 12, 15, 20, 27, 31, 31,\n 12, 12, 14, 19, 27, 31, 31, 31,\n 16, 12, 19, 28, 31, 31, 31, 31],\n [7, 7, 13, 24, 26, 31, 31, 31,\n 7, 12, 16, 21, 31, 31, 31, 31,\n 13, 16, 17, 31, 31, 31, 31, 31,\n 24, 21, 31, 31, 31, 31, 31, 31,\n 26, 31, 31, 31, 31, 31, 31, 31,\n 31, 31, 31, 31, 31, 31, 31, 31,\n 31, 31, 31, 31, 31, 31, 31, 31,\n 31, 31, 31, 31, 31, 31, 31, 31]\n ]},\n 'web_very_high': {'subsampling': 0, # "4:4:4"\n 'quantization': [\n [2, 2, 2, 2, 3, 4, 5, 6,\n 2, 2, 2, 2, 3, 4, 5, 6,\n 2, 2, 2, 2, 4, 5, 7, 9,\n 2, 2, 2, 4, 5, 7, 9, 12,\n 3, 3, 4, 5, 8, 10, 12, 12,\n 4, 4, 5, 7, 10, 12, 12, 12,\n 5, 5, 7, 9, 12, 12, 12, 12,\n 6, 6, 9, 12, 12, 12, 12, 12],\n [3, 3, 5, 9, 13, 15, 15, 15,\n 3, 4, 6, 11, 14, 12, 12, 12,\n 5, 6, 9, 14, 12, 12, 12, 12,\n 9, 11, 14, 12, 12, 12, 12, 12,\n 13, 14, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12]\n ]},\n 'web_maximum': {'subsampling': 0, # "4:4:4"\n 'quantization': [\n [1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 1,\n 1, 1, 1, 1, 1, 1, 1, 2,\n 1, 1, 1, 1, 1, 1, 2, 2,\n 1, 1, 1, 1, 1, 2, 2, 3,\n 1, 1, 1, 1, 2, 2, 3, 3,\n 1, 1, 1, 2, 2, 3, 3, 3,\n 1, 1, 2, 2, 3, 3, 3, 3],\n [1, 1, 1, 2, 2, 3, 3, 3,\n 1, 1, 1, 2, 3, 3, 3, 3,\n 1, 1, 1, 3, 3, 3, 3, 3,\n 2, 2, 3, 3, 3, 3, 3, 3,\n 2, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3,\n 3, 3, 3, 3, 3, 3, 3, 3]\n ]},\n 'low': {'subsampling': 2, # "4:2:0"\n 'quantization': [\n [18, 14, 14, 21, 30, 35, 34, 17,\n 14, 16, 16, 19, 26, 23, 12, 12,\n 14, 16, 17, 21, 23, 12, 12, 12,\n 21, 19, 21, 23, 12, 12, 12, 12,\n 30, 26, 23, 12, 12, 12, 12, 12,\n 35, 23, 12, 12, 12, 12, 12, 12,\n 34, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12],\n [20, 19, 22, 27, 20, 20, 17, 17,\n 19, 25, 23, 14, 14, 12, 12, 12,\n 22, 23, 14, 14, 12, 12, 12, 12,\n 27, 14, 14, 12, 12, 12, 12, 12,\n 20, 14, 12, 12, 12, 12, 12, 12,\n 20, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12]\n ]},\n 'medium': {'subsampling': 2, # "4:2:0"\n 'quantization': [\n [12, 8, 8, 12, 17, 21, 24, 17,\n 8, 9, 9, 11, 15, 19, 12, 12,\n 8, 9, 10, 12, 19, 12, 12, 12,\n 12, 11, 12, 21, 12, 12, 12, 12,\n 17, 15, 19, 12, 12, 12, 12, 12,\n 21, 19, 12, 12, 12, 12, 12, 12,\n 24, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12],\n [13, 11, 13, 16, 20, 20, 17, 17,\n 11, 14, 14, 14, 14, 12, 12, 12,\n 13, 14, 14, 14, 12, 12, 12, 12,\n 16, 14, 14, 12, 12, 12, 12, 12,\n 20, 14, 12, 12, 12, 12, 12, 12,\n 20, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12]\n ]},\n 'high': {'subsampling': 0, # "4:4:4"\n 'quantization': [\n [6, 4, 4, 6, 9, 11, 12, 16,\n 4, 5, 5, 6, 8, 10, 12, 12,\n 4, 5, 5, 6, 10, 12, 12, 12,\n 6, 6, 6, 11, 12, 12, 12, 12,\n 9, 8, 10, 12, 12, 12, 12, 12,\n 11, 10, 12, 12, 12, 12, 12, 12,\n 12, 12, 12, 12, 12, 12, 12, 12,\n 16, 12, 12, 12, 12, 12, 12, 12],\n [7, 7, 13, 24, 20, 20, 17, 17,\n 7, 12, 16, 14, 14, 12, 12, 12,\n 13, 16, 14, 14, 12, 12, 12, 12,\n 24, 14, 14, 12, 12, 12, 12, 12,\n 20, 14, 12, 12, 12, 12, 12, 12,\n 20, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12,\n 17, 12, 12, 12, 12, 12, 12, 12]\n ]},\n 'maximum': {'subsampling': 0, # "4:4:4"\n 'quantization': [\n [2, 2, 2, 2, 3, 4, 5, 6,\n 2, 2, 2, 2, 3, 4, 5, 6,\n 2, 2, 2, 2, 4, 5, 7, 9,\n 2, 2, 2, 4, 5, 7, 9, 12,\n 3, 3, 4, 5, 8, 10, 12, 12,\n 4, 4, 5, 7, 10, 12, 12, 12,\n 5, 5, 7, 9, 12, 12, 12, 12,\n 6, 6, 9, 12, 12, 12, 12, 12],\n [3, 3, 5, 9, 13, 15, 15, 15,\n 3, 4, 6, 10, 14, 12, 12, 12,\n 5, 6, 9, 14, 12, 12, 12, 12,\n 9, 10, 14, 12, 12, 12, 12, 12,\n 13, 14, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12,\n 15, 12, 12, 12, 12, 12, 12, 12]\n ]},\n}\n# fmt: on\n | .venv\Lib\site-packages\PIL\JpegPresets.py | JpegPresets.py | Python | 12,621 | 0.95 | 0.016529 | 0.013825 | awesome-app | 289 | 2024-06-12T14:40:09.462411 | Apache-2.0 | false | 6f6bfa156856b61ad345c43b6dc2c73d |
#\n# The Python Imaging Library.\n# $Id$\n#\n# Basic McIdas support for PIL\n#\n# History:\n# 1997-05-05 fl Created (8-bit images only)\n# 2009-03-08 fl Added 16/32-bit support.\n#\n# Thanks to Richard Jones and Craig Swank for specs and samples.\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1997.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport struct\n\nfrom . import Image, ImageFile\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04")\n\n\n##\n# Image plugin for McIdas area images.\n\n\nclass McIdasImageFile(ImageFile.ImageFile):\n format = "MCIDAS"\n format_description = "McIdas area file"\n\n def _open(self) -> None:\n # parse area file directory\n assert self.fp is not None\n\n s = self.fp.read(256)\n if not _accept(s) or len(s) != 256:\n msg = "not an McIdas area file"\n raise SyntaxError(msg)\n\n self.area_descriptor_raw = s\n self.area_descriptor = w = [0, *struct.unpack("!64i", s)]\n\n # get mode\n if w[11] == 1:\n mode = rawmode = "L"\n elif w[11] == 2:\n mode = rawmode = "I;16B"\n elif w[11] == 4:\n # FIXME: add memory map support\n mode = "I"\n rawmode = "I;32B"\n else:\n msg = "unsupported McIdas format"\n raise SyntaxError(msg)\n\n self._mode = mode\n self._size = w[10], w[9]\n\n offset = w[34] + w[15]\n stride = w[15] + w[10] * w[11] * w[14]\n\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride, 1))\n ]\n\n\n# --------------------------------------------------------------------\n# registry\n\nImage.register_open(McIdasImageFile.format, McIdasImageFile, _accept)\n\n# no default extension\n | .venv\Lib\site-packages\PIL\McIdasImagePlugin.py | McIdasImagePlugin.py | Python | 1,955 | 0.95 | 0.115385 | 0.423729 | awesome-app | 208 | 2024-11-16T15:39:17.551145 | MIT | false | c840f91d0b076a985ff0b661e021bef8 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# Microsoft Image Composer support for PIL\n#\n# Notes:\n# uses TiffImagePlugin.py to read the actual image streams\n#\n# History:\n# 97-01-20 fl Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1997.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport olefile\n\nfrom . import Image, TiffImagePlugin\n\n#\n# --------------------------------------------------------------------\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(olefile.MAGIC)\n\n\n##\n# Image plugin for Microsoft's Image Composer file format.\n\n\nclass MicImageFile(TiffImagePlugin.TiffImageFile):\n format = "MIC"\n format_description = "Microsoft Image Composer"\n _close_exclusive_fp_after_loading = False\n\n def _open(self) -> None:\n # read the OLE directory and see if this is a likely\n # to be a Microsoft Image Composer file\n\n try:\n self.ole = olefile.OleFileIO(self.fp)\n except OSError as e:\n msg = "not an MIC file; invalid OLE file"\n raise SyntaxError(msg) from e\n\n # find ACI subfiles with Image members (maybe not the\n # best way to identify MIC files, but what the... ;-)\n\n self.images = [\n path\n for path in self.ole.listdir()\n if path[1:] and path[0].endswith(".ACI") and path[1] == "Image"\n ]\n\n # if we didn't find any images, this is probably not\n # an MIC file.\n if not self.images:\n msg = "not an MIC file; no image entries"\n raise SyntaxError(msg)\n\n self.frame = -1\n self._n_frames = len(self.images)\n self.is_animated = self._n_frames > 1\n\n self.__fp = self.fp\n self.seek(0)\n\n def seek(self, frame: int) -> None:\n if not self._seek_check(frame):\n return\n filename = self.images[frame]\n self.fp = self.ole.openstream(filename)\n\n TiffImagePlugin.TiffImageFile._open(self)\n\n self.frame = frame\n\n def tell(self) -> int:\n return self.frame\n\n def close(self) -> None:\n self.__fp.close()\n self.ole.close()\n super().close()\n\n def __exit__(self, *args: object) -> None:\n self.__fp.close()\n self.ole.close()\n super().__exit__()\n\n\n#\n# --------------------------------------------------------------------\n\nImage.register_open(MicImageFile.format, MicImageFile, _accept)\n\nImage.register_extension(MicImageFile.format, ".mic")\n | .venv\Lib\site-packages\PIL\MicImagePlugin.py | MicImagePlugin.py | Python | 2,666 | 0.95 | 0.166667 | 0.381579 | vue-tools | 675 | 2024-03-09T09:28:26.455075 | BSD-3-Clause | false | db0194176d5c811d772a73207358cd45 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# MPEG file handling\n#\n# History:\n# 95-09-09 fl Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1995.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFile\nfrom ._binary import i8\nfrom ._typing import SupportsRead\n\n#\n# Bitstream parser\n\n\nclass BitStream:\n def __init__(self, fp: SupportsRead[bytes]) -> None:\n self.fp = fp\n self.bits = 0\n self.bitbuffer = 0\n\n def next(self) -> int:\n return i8(self.fp.read(1))\n\n def peek(self, bits: int) -> int:\n while self.bits < bits:\n self.bitbuffer = (self.bitbuffer << 8) + self.next()\n self.bits += 8\n return self.bitbuffer >> (self.bits - bits) & (1 << bits) - 1\n\n def skip(self, bits: int) -> None:\n while self.bits < bits:\n self.bitbuffer = (self.bitbuffer << 8) + i8(self.fp.read(1))\n self.bits += 8\n self.bits = self.bits - bits\n\n def read(self, bits: int) -> int:\n v = self.peek(bits)\n self.bits = self.bits - bits\n return v\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"\x00\x00\x01\xb3")\n\n\n##\n# Image plugin for MPEG streams. This plugin can identify a stream,\n# but it cannot read it.\n\n\nclass MpegImageFile(ImageFile.ImageFile):\n format = "MPEG"\n format_description = "MPEG"\n\n def _open(self) -> None:\n assert self.fp is not None\n\n s = BitStream(self.fp)\n if s.read(32) != 0x1B3:\n msg = "not an MPEG file"\n raise SyntaxError(msg)\n\n self._mode = "RGB"\n self._size = s.read(12), s.read(12)\n\n\n# --------------------------------------------------------------------\n# Registry stuff\n\nImage.register_open(MpegImageFile.format, MpegImageFile, _accept)\n\nImage.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])\n\nImage.register_mime(MpegImageFile.format, "video/mpeg")\n | .venv\Lib\site-packages\PIL\MpegImagePlugin.py | MpegImagePlugin.py | Python | 2,094 | 0.95 | 0.166667 | 0.33871 | vue-tools | 310 | 2024-07-30T02:30:36.115471 | MIT | false | 8e481563dc088051b14b1b80026ef70a |
#\n# The Python Imaging Library.\n# $Id$\n#\n# MPO file handling\n#\n# See "Multi-Picture Format" (CIPA DC-007-Translation 2009, Standard of the\n# Camera & Imaging Products Association)\n#\n# The multi-picture object combines multiple JPEG images (with a modified EXIF\n# data format) into a single file. While it can theoretically be used much like\n# a GIF animation, it is commonly used to represent 3D photographs and is (as\n# of this writing) the most commonly used format by 3D cameras.\n#\n# History:\n# 2014-03-13 Feneric Created\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport os\nimport struct\nfrom typing import IO, Any, cast\n\nfrom . import (\n Image,\n ImageFile,\n ImageSequence,\n JpegImagePlugin,\n TiffImagePlugin,\n)\nfrom ._binary import o32le\nfrom ._util import DeferredError\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n JpegImagePlugin._save(im, fp, filename)\n\n\ndef _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n append_images = im.encoderinfo.get("append_images", [])\n if not append_images and not getattr(im, "is_animated", False):\n _save(im, fp, filename)\n return\n\n mpf_offset = 28\n offsets: list[int] = []\n im_sequences = [im, *append_images]\n total = sum(getattr(seq, "n_frames", 1) for seq in im_sequences)\n for im_sequence in im_sequences:\n for im_frame in ImageSequence.Iterator(im_sequence):\n if not offsets:\n # APP2 marker\n ifd_length = 66 + 16 * total\n im_frame.encoderinfo["extra"] = (\n b"\xff\xe2"\n + struct.pack(">H", 6 + ifd_length)\n + b"MPF\0"\n + b" " * ifd_length\n )\n exif = im_frame.encoderinfo.get("exif")\n if isinstance(exif, Image.Exif):\n exif = exif.tobytes()\n im_frame.encoderinfo["exif"] = exif\n if exif:\n mpf_offset += 4 + len(exif)\n\n JpegImagePlugin._save(im_frame, fp, filename)\n offsets.append(fp.tell())\n else:\n encoderinfo = im_frame._attach_default_encoderinfo(im)\n im_frame.save(fp, "JPEG")\n im_frame.encoderinfo = encoderinfo\n offsets.append(fp.tell() - offsets[-1])\n\n ifd = TiffImagePlugin.ImageFileDirectory_v2()\n ifd[0xB000] = b"0100"\n ifd[0xB001] = len(offsets)\n\n mpentries = b""\n data_offset = 0\n for i, size in enumerate(offsets):\n if i == 0:\n mptype = 0x030000 # Baseline MP Primary Image\n else:\n mptype = 0x000000 # Undefined\n mpentries += struct.pack("<LLLHH", mptype, size, data_offset, 0, 0)\n if i == 0:\n data_offset -= mpf_offset\n data_offset += size\n ifd[0xB002] = mpentries\n\n fp.seek(mpf_offset)\n fp.write(b"II\x2a\x00" + o32le(8) + ifd.tobytes(8))\n fp.seek(0, os.SEEK_END)\n\n\n##\n# Image plugin for MPO images.\n\n\nclass MpoImageFile(JpegImagePlugin.JpegImageFile):\n format = "MPO"\n format_description = "MPO (CIPA DC-007)"\n _close_exclusive_fp_after_loading = False\n\n def _open(self) -> None:\n self.fp.seek(0) # prep the fp in order to pass the JPEG test\n JpegImagePlugin.JpegImageFile._open(self)\n self._after_jpeg_open()\n\n def _after_jpeg_open(self, mpheader: dict[int, Any] | None = None) -> None:\n self.mpinfo = mpheader if mpheader is not None else self._getmp()\n if self.mpinfo is None:\n msg = "Image appears to be a malformed MPO file"\n raise ValueError(msg)\n self.n_frames = self.mpinfo[0xB001]\n self.__mpoffsets = [\n mpent["DataOffset"] + self.info["mpoffset"] for mpent in self.mpinfo[0xB002]\n ]\n self.__mpoffsets[0] = 0\n # Note that the following assertion will only be invalid if something\n # gets broken within JpegImagePlugin.\n assert self.n_frames == len(self.__mpoffsets)\n del self.info["mpoffset"] # no longer needed\n self.is_animated = self.n_frames > 1\n self._fp = self.fp # FIXME: hack\n self._fp.seek(self.__mpoffsets[0]) # get ready to read first frame\n self.__frame = 0\n self.offset = 0\n # for now we can only handle reading and individual frame extraction\n self.readonly = 1\n\n def load_seek(self, pos: int) -> None:\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n self._fp.seek(pos)\n\n def seek(self, frame: int) -> None:\n if not self._seek_check(frame):\n return\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n self.fp = self._fp\n self.offset = self.__mpoffsets[frame]\n\n original_exif = self.info.get("exif")\n if "exif" in self.info:\n del self.info["exif"]\n\n self.fp.seek(self.offset + 2) # skip SOI marker\n if not self.fp.read(2):\n msg = "No data found for frame"\n raise ValueError(msg)\n self.fp.seek(self.offset)\n JpegImagePlugin.JpegImageFile._open(self)\n if self.info.get("exif") != original_exif:\n self._reload_exif()\n\n self.tile = [\n ImageFile._Tile("jpeg", (0, 0) + self.size, self.offset, self.tile[0][-1])\n ]\n self.__frame = frame\n\n def tell(self) -> int:\n return self.__frame\n\n @staticmethod\n def adopt(\n jpeg_instance: JpegImagePlugin.JpegImageFile,\n mpheader: dict[int, Any] | None = None,\n ) -> MpoImageFile:\n """\n Transform the instance of JpegImageFile into\n an instance of MpoImageFile.\n After the call, the JpegImageFile is extended\n to be an MpoImageFile.\n\n This is essentially useful when opening a JPEG\n file that reveals itself as an MPO, to avoid\n double call to _open.\n """\n jpeg_instance.__class__ = MpoImageFile\n mpo_instance = cast(MpoImageFile, jpeg_instance)\n mpo_instance._after_jpeg_open(mpheader)\n return mpo_instance\n\n\n# ---------------------------------------------------------------------\n# Registry stuff\n\n# Note that since MPO shares a factory with JPEG, we do not need to do a\n# separate registration for it here.\n# Image.register_open(MpoImageFile.format,\n# JpegImagePlugin.jpeg_factory, _accept)\nImage.register_save(MpoImageFile.format, _save)\nImage.register_save_all(MpoImageFile.format, _save_all)\n\nImage.register_extension(MpoImageFile.format, ".mpo")\n\nImage.register_mime(MpoImageFile.format, "image/mpo")\n | .venv\Lib\site-packages\PIL\MpoImagePlugin.py | MpoImagePlugin.py | Python | 6,924 | 0.95 | 0.168317 | 0.180233 | awesome-app | 803 | 2023-09-18T11:40:41.378069 | Apache-2.0 | false | b21a6ddcf3e9c36db77ae91292a43ecc |
#\n# The Python Imaging Library.\n#\n# MSP file handling\n#\n# This is the format used by the Paint program in Windows 1 and 2.\n#\n# History:\n# 95-09-05 fl Created\n# 97-01-03 fl Read/write MSP images\n# 17-02-21 es Fixed RLE interpretation\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1995-97.\n# Copyright (c) Eric Soroos 2017.\n#\n# See the README file for information on usage and redistribution.\n#\n# More info on this format: https://archive.org/details/gg243631\n# Page 313:\n# Figure 205. Windows Paint Version 1: "DanM" Format\n# Figure 206. Windows Paint Version 2: "LinS" Format. Used in Windows V2.03\n#\n# See also: https://www.fileformat.info/format/mspaint/egff.htm\nfrom __future__ import annotations\n\nimport io\nimport struct\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i16le as i16\nfrom ._binary import o16le as o16\n\n#\n# read MSP files\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith((b"DanM", b"LinS"))\n\n\n##\n# Image plugin for Windows MSP images. This plugin supports both\n# uncompressed (Windows 1.0).\n\n\nclass MspImageFile(ImageFile.ImageFile):\n format = "MSP"\n format_description = "Windows Paint"\n\n def _open(self) -> None:\n # Header\n assert self.fp is not None\n\n s = self.fp.read(32)\n if not _accept(s):\n msg = "not an MSP file"\n raise SyntaxError(msg)\n\n # Header checksum\n checksum = 0\n for i in range(0, 32, 2):\n checksum = checksum ^ i16(s, i)\n if checksum != 0:\n msg = "bad MSP checksum"\n raise SyntaxError(msg)\n\n self._mode = "1"\n self._size = i16(s, 4), i16(s, 6)\n\n if s.startswith(b"DanM"):\n self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")]\n else:\n self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)]\n\n\nclass MspDecoder(ImageFile.PyDecoder):\n # The algo for the MSP decoder is from\n # https://www.fileformat.info/format/mspaint/egff.htm\n # cc-by-attribution -- That page references is taken from the\n # Encyclopedia of Graphics File Formats and is licensed by\n # O'Reilly under the Creative Common/Attribution license\n #\n # For RLE encoded files, the 32byte header is followed by a scan\n # line map, encoded as one 16bit word of encoded byte length per\n # line.\n #\n # NOTE: the encoded length of the line can be 0. This was not\n # handled in the previous version of this encoder, and there's no\n # mention of how to handle it in the documentation. From the few\n # examples I've seen, I've assumed that it is a fill of the\n # background color, in this case, white.\n #\n #\n # Pseudocode of the decoder:\n # Read a BYTE value as the RunType\n # If the RunType value is zero\n # Read next byte as the RunCount\n # Read the next byte as the RunValue\n # Write the RunValue byte RunCount times\n # If the RunType value is non-zero\n # Use this value as the RunCount\n # Read and write the next RunCount bytes literally\n #\n # e.g.:\n # 0x00 03 ff 05 00 01 02 03 04\n # would yield the bytes:\n # 0xff ff ff 00 01 02 03 04\n #\n # which are then interpreted as a bit packed mode '1' image\n\n _pulls_fd = True\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n assert self.fd is not None\n\n img = io.BytesIO()\n blank_line = bytearray((0xFF,) * ((self.state.xsize + 7) // 8))\n try:\n self.fd.seek(32)\n rowmap = struct.unpack_from(\n f"<{self.state.ysize}H", self.fd.read(self.state.ysize * 2)\n )\n except struct.error as e:\n msg = "Truncated MSP file in row map"\n raise OSError(msg) from e\n\n for x, rowlen in enumerate(rowmap):\n try:\n if rowlen == 0:\n img.write(blank_line)\n continue\n row = self.fd.read(rowlen)\n if len(row) != rowlen:\n msg = f"Truncated MSP file, expected {rowlen} bytes on row {x}"\n raise OSError(msg)\n idx = 0\n while idx < rowlen:\n runtype = row[idx]\n idx += 1\n if runtype == 0:\n (runcount, runval) = struct.unpack_from("Bc", row, idx)\n img.write(runval * runcount)\n idx += 2\n else:\n runcount = runtype\n img.write(row[idx : idx + runcount])\n idx += runcount\n\n except struct.error as e:\n msg = f"Corrupted MSP file in row {x}"\n raise OSError(msg) from e\n\n self.set_as_raw(img.getvalue(), "1")\n\n return -1, 0\n\n\nImage.register_decoder("MSP", MspDecoder)\n\n\n#\n# write MSP files (uncompressed only)\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode != "1":\n msg = f"cannot write mode {im.mode} as MSP"\n raise OSError(msg)\n\n # create MSP header\n header = [0] * 16\n\n header[0], header[1] = i16(b"Da"), i16(b"nM") # version 1\n header[2], header[3] = im.size\n header[4], header[5] = 1, 1\n header[6], header[7] = 1, 1\n header[8], header[9] = im.size\n\n checksum = 0\n for h in header:\n checksum = checksum ^ h\n header[12] = checksum # FIXME: is this the right field?\n\n # header\n for h in header:\n fp.write(o16(h))\n\n # image body\n ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 32, "1")])\n\n\n#\n# registry\n\nImage.register_open(MspImageFile.format, MspImageFile, _accept)\nImage.register_save(MspImageFile.format, _save)\n\nImage.register_extension(MspImageFile.format, ".msp")\n | .venv\Lib\site-packages\PIL\MspImagePlugin.py | MspImagePlugin.py | Python | 6,092 | 0.95 | 0.115 | 0.438272 | vue-tools | 449 | 2024-09-01T12:51:53.583689 | BSD-3-Clause | false | 8d32611be9c7f9782f256001987811a9 |
#\n# Python Imaging Library\n# $Id$\n#\n# stuff to read simple, teragon-style palette files\n#\n# History:\n# 97-08-23 fl Created\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1997.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom typing import IO\n\nfrom ._binary import o8\n\n\nclass PaletteFile:\n """File handler for Teragon-style palette files."""\n\n rawmode = "RGB"\n\n def __init__(self, fp: IO[bytes]) -> None:\n palette = [o8(i) * 3 for i in range(256)]\n\n while True:\n s = fp.readline()\n\n if not s:\n break\n if s.startswith(b"#"):\n continue\n if len(s) > 100:\n msg = "bad palette file"\n raise SyntaxError(msg)\n\n v = [int(x) for x in s.split()]\n try:\n [i, r, g, b] = v\n except ValueError:\n [i, r] = v\n g = b = r\n\n if 0 <= i <= 255:\n palette[i] = o8(r) + o8(g) + o8(b)\n\n self.palette = b"".join(palette)\n\n def getpalette(self) -> tuple[bytes, str]:\n return self.palette, self.rawmode\n | .venv\Lib\site-packages\PIL\PaletteFile.py | PaletteFile.py | Python | 1,270 | 0.95 | 0.240741 | 0.333333 | react-lib | 544 | 2024-03-19T00:57:46.514714 | MIT | false | b01b137be4d729c9d88349cc4bf0b24b |
#\n# The Python Imaging Library.\n# $Id$\n#\n\n##\n# Image plugin for Palm pixmap images (output only).\n##\nfrom __future__ import annotations\n\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import o8\nfrom ._binary import o16be as o16b\n\n# fmt: off\n_Palm8BitColormapValues = (\n (255, 255, 255), (255, 204, 255), (255, 153, 255), (255, 102, 255),\n (255, 51, 255), (255, 0, 255), (255, 255, 204), (255, 204, 204),\n (255, 153, 204), (255, 102, 204), (255, 51, 204), (255, 0, 204),\n (255, 255, 153), (255, 204, 153), (255, 153, 153), (255, 102, 153),\n (255, 51, 153), (255, 0, 153), (204, 255, 255), (204, 204, 255),\n (204, 153, 255), (204, 102, 255), (204, 51, 255), (204, 0, 255),\n (204, 255, 204), (204, 204, 204), (204, 153, 204), (204, 102, 204),\n (204, 51, 204), (204, 0, 204), (204, 255, 153), (204, 204, 153),\n (204, 153, 153), (204, 102, 153), (204, 51, 153), (204, 0, 153),\n (153, 255, 255), (153, 204, 255), (153, 153, 255), (153, 102, 255),\n (153, 51, 255), (153, 0, 255), (153, 255, 204), (153, 204, 204),\n (153, 153, 204), (153, 102, 204), (153, 51, 204), (153, 0, 204),\n (153, 255, 153), (153, 204, 153), (153, 153, 153), (153, 102, 153),\n (153, 51, 153), (153, 0, 153), (102, 255, 255), (102, 204, 255),\n (102, 153, 255), (102, 102, 255), (102, 51, 255), (102, 0, 255),\n (102, 255, 204), (102, 204, 204), (102, 153, 204), (102, 102, 204),\n (102, 51, 204), (102, 0, 204), (102, 255, 153), (102, 204, 153),\n (102, 153, 153), (102, 102, 153), (102, 51, 153), (102, 0, 153),\n (51, 255, 255), (51, 204, 255), (51, 153, 255), (51, 102, 255),\n (51, 51, 255), (51, 0, 255), (51, 255, 204), (51, 204, 204),\n (51, 153, 204), (51, 102, 204), (51, 51, 204), (51, 0, 204),\n (51, 255, 153), (51, 204, 153), (51, 153, 153), (51, 102, 153),\n (51, 51, 153), (51, 0, 153), (0, 255, 255), (0, 204, 255),\n (0, 153, 255), (0, 102, 255), (0, 51, 255), (0, 0, 255),\n (0, 255, 204), (0, 204, 204), (0, 153, 204), (0, 102, 204),\n (0, 51, 204), (0, 0, 204), (0, 255, 153), (0, 204, 153),\n (0, 153, 153), (0, 102, 153), (0, 51, 153), (0, 0, 153),\n (255, 255, 102), (255, 204, 102), (255, 153, 102), (255, 102, 102),\n (255, 51, 102), (255, 0, 102), (255, 255, 51), (255, 204, 51),\n (255, 153, 51), (255, 102, 51), (255, 51, 51), (255, 0, 51),\n (255, 255, 0), (255, 204, 0), (255, 153, 0), (255, 102, 0),\n (255, 51, 0), (255, 0, 0), (204, 255, 102), (204, 204, 102),\n (204, 153, 102), (204, 102, 102), (204, 51, 102), (204, 0, 102),\n (204, 255, 51), (204, 204, 51), (204, 153, 51), (204, 102, 51),\n (204, 51, 51), (204, 0, 51), (204, 255, 0), (204, 204, 0),\n (204, 153, 0), (204, 102, 0), (204, 51, 0), (204, 0, 0),\n (153, 255, 102), (153, 204, 102), (153, 153, 102), (153, 102, 102),\n (153, 51, 102), (153, 0, 102), (153, 255, 51), (153, 204, 51),\n (153, 153, 51), (153, 102, 51), (153, 51, 51), (153, 0, 51),\n (153, 255, 0), (153, 204, 0), (153, 153, 0), (153, 102, 0),\n (153, 51, 0), (153, 0, 0), (102, 255, 102), (102, 204, 102),\n (102, 153, 102), (102, 102, 102), (102, 51, 102), (102, 0, 102),\n (102, 255, 51), (102, 204, 51), (102, 153, 51), (102, 102, 51),\n (102, 51, 51), (102, 0, 51), (102, 255, 0), (102, 204, 0),\n (102, 153, 0), (102, 102, 0), (102, 51, 0), (102, 0, 0),\n (51, 255, 102), (51, 204, 102), (51, 153, 102), (51, 102, 102),\n (51, 51, 102), (51, 0, 102), (51, 255, 51), (51, 204, 51),\n (51, 153, 51), (51, 102, 51), (51, 51, 51), (51, 0, 51),\n (51, 255, 0), (51, 204, 0), (51, 153, 0), (51, 102, 0),\n (51, 51, 0), (51, 0, 0), (0, 255, 102), (0, 204, 102),\n (0, 153, 102), (0, 102, 102), (0, 51, 102), (0, 0, 102),\n (0, 255, 51), (0, 204, 51), (0, 153, 51), (0, 102, 51),\n (0, 51, 51), (0, 0, 51), (0, 255, 0), (0, 204, 0),\n (0, 153, 0), (0, 102, 0), (0, 51, 0), (17, 17, 17),\n (34, 34, 34), (68, 68, 68), (85, 85, 85), (119, 119, 119),\n (136, 136, 136), (170, 170, 170), (187, 187, 187), (221, 221, 221),\n (238, 238, 238), (192, 192, 192), (128, 0, 0), (128, 0, 128),\n (0, 128, 0), (0, 128, 128), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0),\n (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0))\n# fmt: on\n\n\n# so build a prototype image to be used for palette resampling\ndef build_prototype_image() -> Image.Image:\n image = Image.new("L", (1, len(_Palm8BitColormapValues)))\n image.putdata(list(range(len(_Palm8BitColormapValues))))\n palettedata: tuple[int, ...] = ()\n for colormapValue in _Palm8BitColormapValues:\n palettedata += colormapValue\n palettedata += (0, 0, 0) * (256 - len(_Palm8BitColormapValues))\n image.putpalette(palettedata)\n return image\n\n\nPalm8BitColormapImage = build_prototype_image()\n\n# OK, we now have in Palm8BitColormapImage,\n# a "P"-mode image with the right palette\n#\n# --------------------------------------------------------------------\n\n_FLAGS = {"custom-colormap": 0x4000, "is-compressed": 0x8000, "has-transparent": 0x2000}\n\n_COMPRESSION_TYPES = {"none": 0xFF, "rle": 0x01, "scanline": 0x00}\n\n\n#\n# --------------------------------------------------------------------\n\n##\n# (Internal) Image save plugin for the Palm format.\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode == "P":\n rawmode = "P"\n bpp = 8\n version = 1\n\n elif im.mode == "L":\n if im.encoderinfo.get("bpp") in (1, 2, 4):\n # this is 8-bit grayscale, so we shift it to get the high-order bits,\n # and invert it because\n # Palm does grayscale from white (0) to black (1)\n bpp = im.encoderinfo["bpp"]\n maxval = (1 << bpp) - 1\n shift = 8 - bpp\n im = im.point(lambda x: maxval - (x >> shift))\n elif im.info.get("bpp") in (1, 2, 4):\n # here we assume that even though the inherent mode is 8-bit grayscale,\n # only the lower bpp bits are significant.\n # We invert them to match the Palm.\n bpp = im.info["bpp"]\n maxval = (1 << bpp) - 1\n im = im.point(lambda x: maxval - (x & maxval))\n else:\n msg = f"cannot write mode {im.mode} as Palm"\n raise OSError(msg)\n\n # we ignore the palette here\n im._mode = "P"\n rawmode = f"P;{bpp}"\n version = 1\n\n elif im.mode == "1":\n # monochrome -- write it inverted, as is the Palm standard\n rawmode = "1;I"\n bpp = 1\n version = 0\n\n else:\n msg = f"cannot write mode {im.mode} as Palm"\n raise OSError(msg)\n\n #\n # make sure image data is available\n im.load()\n\n # write header\n\n cols = im.size[0]\n rows = im.size[1]\n\n rowbytes = int((cols + (16 // bpp - 1)) / (16 // bpp)) * 2\n transparent_index = 0\n compression_type = _COMPRESSION_TYPES["none"]\n\n flags = 0\n if im.mode == "P":\n flags |= _FLAGS["custom-colormap"]\n colormap = im.im.getpalette()\n colors = len(colormap) // 3\n colormapsize = 4 * colors + 2\n else:\n colormapsize = 0\n\n if "offset" in im.info:\n offset = (rowbytes * rows + 16 + 3 + colormapsize) // 4\n else:\n offset = 0\n\n fp.write(o16b(cols) + o16b(rows) + o16b(rowbytes) + o16b(flags))\n fp.write(o8(bpp))\n fp.write(o8(version))\n fp.write(o16b(offset))\n fp.write(o8(transparent_index))\n fp.write(o8(compression_type))\n fp.write(o16b(0)) # reserved by Palm\n\n # now write colormap if necessary\n\n if colormapsize:\n fp.write(o16b(colors))\n for i in range(colors):\n fp.write(o8(i))\n fp.write(colormap[3 * i : 3 * i + 3])\n\n # now convert data to raw form\n ImageFile._save(\n im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, rowbytes, 1))]\n )\n\n if hasattr(fp, "flush"):\n fp.flush()\n\n\n#\n# --------------------------------------------------------------------\n\nImage.register_save("Palm", _save)\n\nImage.register_extension("Palm", ".palm")\n\nImage.register_mime("Palm", "image/palm")\n | .venv\Lib\site-packages\PIL\PalmImagePlugin.py | PalmImagePlugin.py | Python | 8,965 | 0.95 | 0.064516 | 0.18232 | vue-tools | 945 | 2024-11-24T03:14:56.547956 | MIT | false | 3ff0b253bb11b859f8b1193c5c0f1c25 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PCD file handling\n#\n# History:\n# 96-05-10 fl Created\n# 96-05-27 fl Added draft mode (128x192, 256x384)\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFile\n\n##\n# Image plugin for PhotoCD images. This plugin only reads the 768x512\n# image from the file; higher resolutions are encoded in a proprietary\n# encoding.\n\n\nclass PcdImageFile(ImageFile.ImageFile):\n format = "PCD"\n format_description = "Kodak PhotoCD"\n\n def _open(self) -> None:\n # rough\n assert self.fp is not None\n\n self.fp.seek(2048)\n s = self.fp.read(2048)\n\n if not s.startswith(b"PCD_"):\n msg = "not a PCD file"\n raise SyntaxError(msg)\n\n orientation = s[1538] & 3\n self.tile_post_rotate = None\n if orientation == 1:\n self.tile_post_rotate = 90\n elif orientation == 3:\n self.tile_post_rotate = -90\n\n self._mode = "RGB"\n self._size = 768, 512 # FIXME: not correct for rotated images!\n self.tile = [ImageFile._Tile("pcd", (0, 0) + self.size, 96 * 2048)]\n\n def load_end(self) -> None:\n if self.tile_post_rotate:\n # Handle rotated PCDs\n self.im = self.im.rotate(self.tile_post_rotate)\n self._size = self.im.size\n\n\n#\n# registry\n\nImage.register_open(PcdImageFile.format, PcdImageFile)\n\nImage.register_extension(PcdImageFile.format, ".pcd")\n | .venv\Lib\site-packages\PIL\PcdImagePlugin.py | PcdImagePlugin.py | Python | 1,665 | 0.95 | 0.140625 | 0.46 | vue-tools | 961 | 2024-05-09T19:06:30.552907 | Apache-2.0 | false | 6aa21d9b314bd85ceab89b04f6d85fd3 |
#\n# THIS IS WORK IN PROGRESS\n#\n# The Python Imaging Library\n# $Id$\n#\n# portable compiled font file parser\n#\n# history:\n# 1997-08-19 fl created\n# 2003-09-13 fl fixed loading of unicode fonts\n#\n# Copyright (c) 1997-2003 by Secret Labs AB.\n# Copyright (c) 1997-2003 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nfrom typing import BinaryIO, Callable\n\nfrom . import FontFile, Image\nfrom ._binary import i8\nfrom ._binary import i16be as b16\nfrom ._binary import i16le as l16\nfrom ._binary import i32be as b32\nfrom ._binary import i32le as l32\n\n# --------------------------------------------------------------------\n# declarations\n\nPCF_MAGIC = 0x70636601 # "\x01fcp"\n\nPCF_PROPERTIES = 1 << 0\nPCF_ACCELERATORS = 1 << 1\nPCF_METRICS = 1 << 2\nPCF_BITMAPS = 1 << 3\nPCF_INK_METRICS = 1 << 4\nPCF_BDF_ENCODINGS = 1 << 5\nPCF_SWIDTHS = 1 << 6\nPCF_GLYPH_NAMES = 1 << 7\nPCF_BDF_ACCELERATORS = 1 << 8\n\nBYTES_PER_ROW: list[Callable[[int], int]] = [\n lambda bits: ((bits + 7) >> 3),\n lambda bits: ((bits + 15) >> 3) & ~1,\n lambda bits: ((bits + 31) >> 3) & ~3,\n lambda bits: ((bits + 63) >> 3) & ~7,\n]\n\n\ndef sz(s: bytes, o: int) -> bytes:\n return s[o : s.index(b"\0", o)]\n\n\nclass PcfFontFile(FontFile.FontFile):\n """Font file plugin for the X11 PCF format."""\n\n name = "name"\n\n def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"):\n self.charset_encoding = charset_encoding\n\n magic = l32(fp.read(4))\n if magic != PCF_MAGIC:\n msg = "not a PCF file"\n raise SyntaxError(msg)\n\n super().__init__()\n\n count = l32(fp.read(4))\n self.toc = {}\n for i in range(count):\n type = l32(fp.read(4))\n self.toc[type] = l32(fp.read(4)), l32(fp.read(4)), l32(fp.read(4))\n\n self.fp = fp\n\n self.info = self._load_properties()\n\n metrics = self._load_metrics()\n bitmaps = self._load_bitmaps(metrics)\n encoding = self._load_encoding()\n\n #\n # create glyph structure\n\n for ch, ix in enumerate(encoding):\n if ix is not None:\n (\n xsize,\n ysize,\n left,\n right,\n width,\n ascent,\n descent,\n attributes,\n ) = metrics[ix]\n self.glyph[ch] = (\n (width, 0),\n (left, descent - ysize, xsize + left, descent),\n (0, 0, xsize, ysize),\n bitmaps[ix],\n )\n\n def _getformat(\n self, tag: int\n ) -> tuple[BinaryIO, int, Callable[[bytes], int], Callable[[bytes], int]]:\n format, size, offset = self.toc[tag]\n\n fp = self.fp\n fp.seek(offset)\n\n format = l32(fp.read(4))\n\n if format & 4:\n i16, i32 = b16, b32\n else:\n i16, i32 = l16, l32\n\n return fp, format, i16, i32\n\n def _load_properties(self) -> dict[bytes, bytes | int]:\n #\n # font properties\n\n properties = {}\n\n fp, format, i16, i32 = self._getformat(PCF_PROPERTIES)\n\n nprops = i32(fp.read(4))\n\n # read property description\n p = [(i32(fp.read(4)), i8(fp.read(1)), i32(fp.read(4))) for _ in range(nprops)]\n\n if nprops & 3:\n fp.seek(4 - (nprops & 3), io.SEEK_CUR) # pad\n\n data = fp.read(i32(fp.read(4)))\n\n for k, s, v in p:\n property_value: bytes | int = sz(data, v) if s else v\n properties[sz(data, k)] = property_value\n\n return properties\n\n def _load_metrics(self) -> list[tuple[int, int, int, int, int, int, int, int]]:\n #\n # font metrics\n\n metrics: list[tuple[int, int, int, int, int, int, int, int]] = []\n\n fp, format, i16, i32 = self._getformat(PCF_METRICS)\n\n append = metrics.append\n\n if (format & 0xFF00) == 0x100:\n # "compressed" metrics\n for i in range(i16(fp.read(2))):\n left = i8(fp.read(1)) - 128\n right = i8(fp.read(1)) - 128\n width = i8(fp.read(1)) - 128\n ascent = i8(fp.read(1)) - 128\n descent = i8(fp.read(1)) - 128\n xsize = right - left\n ysize = ascent + descent\n append((xsize, ysize, left, right, width, ascent, descent, 0))\n\n else:\n # "jumbo" metrics\n for i in range(i32(fp.read(4))):\n left = i16(fp.read(2))\n right = i16(fp.read(2))\n width = i16(fp.read(2))\n ascent = i16(fp.read(2))\n descent = i16(fp.read(2))\n attributes = i16(fp.read(2))\n xsize = right - left\n ysize = ascent + descent\n append((xsize, ysize, left, right, width, ascent, descent, attributes))\n\n return metrics\n\n def _load_bitmaps(\n self, metrics: list[tuple[int, int, int, int, int, int, int, int]]\n ) -> list[Image.Image]:\n #\n # bitmap data\n\n fp, format, i16, i32 = self._getformat(PCF_BITMAPS)\n\n nbitmaps = i32(fp.read(4))\n\n if nbitmaps != len(metrics):\n msg = "Wrong number of bitmaps"\n raise OSError(msg)\n\n offsets = [i32(fp.read(4)) for _ in range(nbitmaps)]\n\n bitmap_sizes = [i32(fp.read(4)) for _ in range(4)]\n\n # byteorder = format & 4 # non-zero => MSB\n bitorder = format & 8 # non-zero => MSB\n padindex = format & 3\n\n bitmapsize = bitmap_sizes[padindex]\n offsets.append(bitmapsize)\n\n data = fp.read(bitmapsize)\n\n pad = BYTES_PER_ROW[padindex]\n mode = "1;R"\n if bitorder:\n mode = "1"\n\n bitmaps = []\n for i in range(nbitmaps):\n xsize, ysize = metrics[i][:2]\n b, e = offsets[i : i + 2]\n bitmaps.append(\n Image.frombytes("1", (xsize, ysize), data[b:e], "raw", mode, pad(xsize))\n )\n\n return bitmaps\n\n def _load_encoding(self) -> list[int | None]:\n fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)\n\n first_col, last_col = i16(fp.read(2)), i16(fp.read(2))\n first_row, last_row = i16(fp.read(2)), i16(fp.read(2))\n\n i16(fp.read(2)) # default\n\n nencoding = (last_col - first_col + 1) * (last_row - first_row + 1)\n\n # map character code to bitmap index\n encoding: list[int | None] = [None] * min(256, nencoding)\n\n encoding_offsets = [i16(fp.read(2)) for _ in range(nencoding)]\n\n for i in range(first_col, len(encoding)):\n try:\n encoding_offset = encoding_offsets[\n ord(bytearray([i]).decode(self.charset_encoding))\n ]\n if encoding_offset != 0xFFFF:\n encoding[i] = encoding_offset\n except UnicodeDecodeError:\n # character is not supported in selected encoding\n pass\n\n return encoding\n | .venv\Lib\site-packages\PIL\PcfFontFile.py | PcfFontFile.py | Python | 7,401 | 0.95 | 0.122047 | 0.170984 | python-kit | 367 | 2024-08-18T00:45:07.034050 | BSD-3-Clause | false | 444c210e07ba1f45d609c9ad0376e4dc |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PCX file handling\n#\n# This format was originally used by ZSoft's popular PaintBrush\n# program for the IBM PC. It is also supported by many MS-DOS and\n# Windows applications, including the Windows PaintBrush program in\n# Windows 3.\n#\n# history:\n# 1995-09-01 fl Created\n# 1996-05-20 fl Fixed RGB support\n# 1997-01-03 fl Fixed 2-bit and 4-bit support\n# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)\n# 1999-02-07 fl Added write support\n# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust\n# 2002-07-30 fl Seek from to current position, not beginning of file\n# 2003-06-03 fl Extract DPI settings (info["dpi"])\n#\n# Copyright (c) 1997-2003 by Secret Labs AB.\n# Copyright (c) 1995-2003 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport logging\nfrom typing import IO\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i16le as i16\nfrom ._binary import o8\nfrom ._binary import o16le as o16\n\nlogger = logging.getLogger(__name__)\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]\n\n\n##\n# Image plugin for Paintbrush images.\n\n\nclass PcxImageFile(ImageFile.ImageFile):\n format = "PCX"\n format_description = "Paintbrush"\n\n def _open(self) -> None:\n # header\n assert self.fp is not None\n\n s = self.fp.read(68)\n if not _accept(s):\n msg = "not a PCX file"\n raise SyntaxError(msg)\n\n # image\n bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1\n if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:\n msg = "bad PCX image size"\n raise SyntaxError(msg)\n logger.debug("BBox: %s %s %s %s", *bbox)\n\n offset = self.fp.tell() + 60\n\n # format\n version = s[1]\n bits = s[3]\n planes = s[65]\n provided_stride = i16(s, 66)\n logger.debug(\n "PCX version %s, bits %s, planes %s, stride %s",\n version,\n bits,\n planes,\n provided_stride,\n )\n\n self.info["dpi"] = i16(s, 12), i16(s, 14)\n\n if bits == 1 and planes == 1:\n mode = rawmode = "1"\n\n elif bits == 1 and planes in (2, 4):\n mode = "P"\n rawmode = f"P;{planes}L"\n self.palette = ImagePalette.raw("RGB", s[16:64])\n\n elif version == 5 and bits == 8 and planes == 1:\n mode = rawmode = "L"\n # FIXME: hey, this doesn't work with the incremental loader !!!\n self.fp.seek(-769, io.SEEK_END)\n s = self.fp.read(769)\n if len(s) == 769 and s[0] == 12:\n # check if the palette is linear grayscale\n for i in range(256):\n if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:\n mode = rawmode = "P"\n break\n if mode == "P":\n self.palette = ImagePalette.raw("RGB", s[1:])\n\n elif version == 5 and bits == 8 and planes == 3:\n mode = "RGB"\n rawmode = "RGB;L"\n\n else:\n msg = "unknown PCX mode"\n raise OSError(msg)\n\n self._mode = mode\n self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]\n\n # Don't trust the passed in stride.\n # Calculate the approximate position for ourselves.\n # CVE-2020-35653\n stride = (self._size[0] * bits + 7) // 8\n\n # While the specification states that this must be even,\n # not all images follow this\n if provided_stride != stride:\n stride += stride % 2\n\n bbox = (0, 0) + self.size\n logger.debug("size: %sx%s", *self.size)\n\n self.tile = [ImageFile._Tile("pcx", bbox, offset, (rawmode, planes * stride))]\n\n\n# --------------------------------------------------------------------\n# save PCX files\n\n\nSAVE = {\n # mode: (version, bits, planes, raw mode)\n "1": (2, 1, 1, "1"),\n "L": (5, 8, 1, "L"),\n "P": (5, 8, 1, "P"),\n "RGB": (5, 8, 3, "RGB;L"),\n}\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n try:\n version, bits, planes, rawmode = SAVE[im.mode]\n except KeyError as e:\n msg = f"Cannot save {im.mode} images as PCX"\n raise ValueError(msg) from e\n\n # bytes per plane\n stride = (im.size[0] * bits + 7) // 8\n # stride should be even\n stride += stride % 2\n # Stride needs to be kept in sync with the PcxEncode.c version.\n # Ideally it should be passed in in the state, but the bytes value\n # gets overwritten.\n\n logger.debug(\n "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",\n im.size[0],\n bits,\n stride,\n )\n\n # under windows, we could determine the current screen size with\n # "Image.core.display_mode()[1]", but I think that's overkill...\n\n screen = im.size\n\n dpi = 100, 100\n\n # PCX header\n fp.write(\n o8(10)\n + o8(version)\n + o8(1)\n + o8(bits)\n + o16(0)\n + o16(0)\n + o16(im.size[0] - 1)\n + o16(im.size[1] - 1)\n + o16(dpi[0])\n + o16(dpi[1])\n + b"\0" * 24\n + b"\xff" * 24\n + b"\0"\n + o8(planes)\n + o16(stride)\n + o16(1)\n + o16(screen[0])\n + o16(screen[1])\n + b"\0" * 54\n )\n\n assert fp.tell() == 128\n\n ImageFile._save(\n im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))]\n )\n\n if im.mode == "P":\n # colour palette\n fp.write(o8(12))\n palette = im.im.getpalette("RGB", "RGB")\n palette += b"\x00" * (768 - len(palette))\n fp.write(palette) # 768 bytes\n elif im.mode == "L":\n # grayscale palette\n fp.write(o8(12))\n for i in range(256):\n fp.write(o8(i) * 3)\n\n\n# --------------------------------------------------------------------\n# registry\n\n\nImage.register_open(PcxImageFile.format, PcxImageFile, _accept)\nImage.register_save(PcxImageFile.format, _save)\n\nImage.register_extension(PcxImageFile.format, ".pcx")\n\nImage.register_mime(PcxImageFile.format, "image/x-pcx")\n | .venv\Lib\site-packages\PIL\PcxImagePlugin.py | PcxImagePlugin.py | Python | 6,452 | 0.95 | 0.087719 | 0.291209 | vue-tools | 462 | 2025-04-28T14:34:19.393124 | MIT | false | 780e800bb27a159be5f0b6c5bc721c5a |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PDF (Acrobat) file handling\n#\n# History:\n# 1996-07-16 fl Created\n# 1997-01-18 fl Fixed header\n# 2004-02-21 fl Fixes for 1/L/CMYK images, etc.\n# 2004-02-24 fl Fixes for 1 and P images.\n#\n# Copyright (c) 1997-2004 by Secret Labs AB. All rights reserved.\n# Copyright (c) 1996-1997 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n# Image plugin for PDF images (output only).\n##\nfrom __future__ import annotations\n\nimport io\nimport math\nimport os\nimport time\nfrom typing import IO, Any\n\nfrom . import Image, ImageFile, ImageSequence, PdfParser, __version__, features\n\n#\n# --------------------------------------------------------------------\n\n# object ids:\n# 1. catalogue\n# 2. pages\n# 3. image\n# 4. page\n# 5. page contents\n\n\ndef _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n _save(im, fp, filename, save_all=True)\n\n\n##\n# (Internal) Image save plugin for the PDF format.\n\n\ndef _write_image(\n im: Image.Image,\n filename: str | bytes,\n existing_pdf: PdfParser.PdfParser,\n image_refs: list[PdfParser.IndirectReference],\n) -> tuple[PdfParser.IndirectReference, str]:\n # FIXME: Should replace ASCIIHexDecode with RunLengthDecode\n # (packbits) or LZWDecode (tiff/lzw compression). Note that\n # PDF 1.2 also supports Flatedecode (zip compression).\n\n params = None\n decode = None\n\n #\n # Get image characteristics\n\n width, height = im.size\n\n dict_obj: dict[str, Any] = {"BitsPerComponent": 8}\n if im.mode == "1":\n if features.check("libtiff"):\n decode_filter = "CCITTFaxDecode"\n dict_obj["BitsPerComponent"] = 1\n params = PdfParser.PdfArray(\n [\n PdfParser.PdfDict(\n {\n "K": -1,\n "BlackIs1": True,\n "Columns": width,\n "Rows": height,\n }\n )\n ]\n )\n else:\n decode_filter = "DCTDecode"\n dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")\n procset = "ImageB" # grayscale\n elif im.mode == "L":\n decode_filter = "DCTDecode"\n # params = f"<< /Predictor 15 /Columns {width-2} >>"\n dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceGray")\n procset = "ImageB" # grayscale\n elif im.mode == "LA":\n decode_filter = "JPXDecode"\n # params = f"<< /Predictor 15 /Columns {width-2} >>"\n procset = "ImageB" # grayscale\n dict_obj["SMaskInData"] = 1\n elif im.mode == "P":\n decode_filter = "ASCIIHexDecode"\n palette = im.getpalette()\n assert palette is not None\n dict_obj["ColorSpace"] = [\n PdfParser.PdfName("Indexed"),\n PdfParser.PdfName("DeviceRGB"),\n len(palette) // 3 - 1,\n PdfParser.PdfBinary(palette),\n ]\n procset = "ImageI" # indexed color\n\n if "transparency" in im.info:\n smask = im.convert("LA").getchannel("A")\n smask.encoderinfo = {}\n\n image_ref = _write_image(smask, filename, existing_pdf, image_refs)[0]\n dict_obj["SMask"] = image_ref\n elif im.mode == "RGB":\n decode_filter = "DCTDecode"\n dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceRGB")\n procset = "ImageC" # color images\n elif im.mode == "RGBA":\n decode_filter = "JPXDecode"\n procset = "ImageC" # color images\n dict_obj["SMaskInData"] = 1\n elif im.mode == "CMYK":\n decode_filter = "DCTDecode"\n dict_obj["ColorSpace"] = PdfParser.PdfName("DeviceCMYK")\n procset = "ImageC" # color images\n decode = [1, 0, 1, 0, 1, 0, 1, 0]\n else:\n msg = f"cannot save mode {im.mode}"\n raise ValueError(msg)\n\n #\n # image\n\n op = io.BytesIO()\n\n if decode_filter == "ASCIIHexDecode":\n ImageFile._save(im, op, [ImageFile._Tile("hex", (0, 0) + im.size, 0, im.mode)])\n elif decode_filter == "CCITTFaxDecode":\n im.save(\n op,\n "TIFF",\n compression="group4",\n # use a single strip\n strip_size=math.ceil(width / 8) * height,\n )\n elif decode_filter == "DCTDecode":\n Image.SAVE["JPEG"](im, op, filename)\n elif decode_filter == "JPXDecode":\n del dict_obj["BitsPerComponent"]\n Image.SAVE["JPEG2000"](im, op, filename)\n else:\n msg = f"unsupported PDF filter ({decode_filter})"\n raise ValueError(msg)\n\n stream = op.getvalue()\n filter: PdfParser.PdfArray | PdfParser.PdfName\n if decode_filter == "CCITTFaxDecode":\n stream = stream[8:]\n filter = PdfParser.PdfArray([PdfParser.PdfName(decode_filter)])\n else:\n filter = PdfParser.PdfName(decode_filter)\n\n image_ref = image_refs.pop(0)\n existing_pdf.write_obj(\n image_ref,\n stream=stream,\n Type=PdfParser.PdfName("XObject"),\n Subtype=PdfParser.PdfName("Image"),\n Width=width, # * 72.0 / x_resolution,\n Height=height, # * 72.0 / y_resolution,\n Filter=filter,\n Decode=decode,\n DecodeParms=params,\n **dict_obj,\n )\n\n return image_ref, procset\n\n\ndef _save(\n im: Image.Image, fp: IO[bytes], filename: str | bytes, save_all: bool = False\n) -> None:\n is_appending = im.encoderinfo.get("append", False)\n filename_str = filename.decode() if isinstance(filename, bytes) else filename\n if is_appending:\n existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="r+b")\n else:\n existing_pdf = PdfParser.PdfParser(f=fp, filename=filename_str, mode="w+b")\n\n dpi = im.encoderinfo.get("dpi")\n if dpi:\n x_resolution = dpi[0]\n y_resolution = dpi[1]\n else:\n x_resolution = y_resolution = im.encoderinfo.get("resolution", 72.0)\n\n info = {\n "title": (\n None if is_appending else os.path.splitext(os.path.basename(filename))[0]\n ),\n "author": None,\n "subject": None,\n "keywords": None,\n "creator": None,\n "producer": None,\n "creationDate": None if is_appending else time.gmtime(),\n "modDate": None if is_appending else time.gmtime(),\n }\n for k, default in info.items():\n v = im.encoderinfo.get(k) if k in im.encoderinfo else default\n if v:\n existing_pdf.info[k[0].upper() + k[1:]] = v\n\n #\n # make sure image data is available\n im.load()\n\n existing_pdf.start_writing()\n existing_pdf.write_header()\n existing_pdf.write_comment(f"created by Pillow {__version__} PDF driver")\n\n #\n # pages\n ims = [im]\n if save_all:\n append_images = im.encoderinfo.get("append_images", [])\n for append_im in append_images:\n append_im.encoderinfo = im.encoderinfo.copy()\n ims.append(append_im)\n number_of_pages = 0\n image_refs = []\n page_refs = []\n contents_refs = []\n for im in ims:\n im_number_of_pages = 1\n if save_all:\n im_number_of_pages = getattr(im, "n_frames", 1)\n number_of_pages += im_number_of_pages\n for i in range(im_number_of_pages):\n image_refs.append(existing_pdf.next_object_id(0))\n if im.mode == "P" and "transparency" in im.info:\n image_refs.append(existing_pdf.next_object_id(0))\n\n page_refs.append(existing_pdf.next_object_id(0))\n contents_refs.append(existing_pdf.next_object_id(0))\n existing_pdf.pages.append(page_refs[-1])\n\n #\n # catalog and list of pages\n existing_pdf.write_catalog()\n\n page_number = 0\n for im_sequence in ims:\n im_pages: ImageSequence.Iterator | list[Image.Image] = (\n ImageSequence.Iterator(im_sequence) if save_all else [im_sequence]\n )\n for im in im_pages:\n image_ref, procset = _write_image(im, filename, existing_pdf, image_refs)\n\n #\n # page\n\n existing_pdf.write_page(\n page_refs[page_number],\n Resources=PdfParser.PdfDict(\n ProcSet=[PdfParser.PdfName("PDF"), PdfParser.PdfName(procset)],\n XObject=PdfParser.PdfDict(image=image_ref),\n ),\n MediaBox=[\n 0,\n 0,\n im.width * 72.0 / x_resolution,\n im.height * 72.0 / y_resolution,\n ],\n Contents=contents_refs[page_number],\n )\n\n #\n # page contents\n\n page_contents = b"q %f 0 0 %f 0 0 cm /image Do Q\n" % (\n im.width * 72.0 / x_resolution,\n im.height * 72.0 / y_resolution,\n )\n\n existing_pdf.write_obj(contents_refs[page_number], stream=page_contents)\n\n page_number += 1\n\n #\n # trailer\n existing_pdf.write_xref_and_trailer()\n if hasattr(fp, "flush"):\n fp.flush()\n existing_pdf.close()\n\n\n#\n# --------------------------------------------------------------------\n\n\nImage.register_save("PDF", _save)\nImage.register_save_all("PDF", _save_all)\n\nImage.register_extension("PDF", ".pdf")\n\nImage.register_mime("PDF", "application/pdf")\n | .venv\Lib\site-packages\PIL\PdfImagePlugin.py | PdfImagePlugin.py | Python | 9,660 | 0.95 | 0.102894 | 0.207547 | react-lib | 831 | 2024-11-15T08:40:31.195786 | GPL-3.0 | false | 7d8bc063ea0ef21963e0298bfe2b48fb |
from __future__ import annotations\n\nimport calendar\nimport codecs\nimport collections\nimport mmap\nimport os\nimport re\nimport time\nimport zlib\nfrom typing import IO, Any, NamedTuple, Union\n\n\n# see 7.9.2.2 Text String Type on page 86 and D.3 PDFDocEncoding Character Set\n# on page 656\ndef encode_text(s: str) -> bytes:\n return codecs.BOM_UTF16_BE + s.encode("utf_16_be")\n\n\nPDFDocEncoding = {\n 0x16: "\u0017",\n 0x18: "\u02d8",\n 0x19: "\u02c7",\n 0x1A: "\u02c6",\n 0x1B: "\u02d9",\n 0x1C: "\u02dd",\n 0x1D: "\u02db",\n 0x1E: "\u02da",\n 0x1F: "\u02dc",\n 0x80: "\u2022",\n 0x81: "\u2020",\n 0x82: "\u2021",\n 0x83: "\u2026",\n 0x84: "\u2014",\n 0x85: "\u2013",\n 0x86: "\u0192",\n 0x87: "\u2044",\n 0x88: "\u2039",\n 0x89: "\u203a",\n 0x8A: "\u2212",\n 0x8B: "\u2030",\n 0x8C: "\u201e",\n 0x8D: "\u201c",\n 0x8E: "\u201d",\n 0x8F: "\u2018",\n 0x90: "\u2019",\n 0x91: "\u201a",\n 0x92: "\u2122",\n 0x93: "\ufb01",\n 0x94: "\ufb02",\n 0x95: "\u0141",\n 0x96: "\u0152",\n 0x97: "\u0160",\n 0x98: "\u0178",\n 0x99: "\u017d",\n 0x9A: "\u0131",\n 0x9B: "\u0142",\n 0x9C: "\u0153",\n 0x9D: "\u0161",\n 0x9E: "\u017e",\n 0xA0: "\u20ac",\n}\n\n\ndef decode_text(b: bytes) -> str:\n if b[: len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:\n return b[len(codecs.BOM_UTF16_BE) :].decode("utf_16_be")\n else:\n return "".join(PDFDocEncoding.get(byte, chr(byte)) for byte in b)\n\n\nclass PdfFormatError(RuntimeError):\n """An error that probably indicates a syntactic or semantic error in the\n PDF file structure"""\n\n pass\n\n\ndef check_format_condition(condition: bool, error_message: str) -> None:\n if not condition:\n raise PdfFormatError(error_message)\n\n\nclass IndirectReferenceTuple(NamedTuple):\n object_id: int\n generation: int\n\n\nclass IndirectReference(IndirectReferenceTuple):\n def __str__(self) -> str:\n return f"{self.object_id} {self.generation} R"\n\n def __bytes__(self) -> bytes:\n return self.__str__().encode("us-ascii")\n\n def __eq__(self, other: object) -> bool:\n if self.__class__ is not other.__class__:\n return False\n assert isinstance(other, IndirectReference)\n return other.object_id == self.object_id and other.generation == self.generation\n\n def __ne__(self, other: object) -> bool:\n return not (self == other)\n\n def __hash__(self) -> int:\n return hash((self.object_id, self.generation))\n\n\nclass IndirectObjectDef(IndirectReference):\n def __str__(self) -> str:\n return f"{self.object_id} {self.generation} obj"\n\n\nclass XrefTable:\n def __init__(self) -> None:\n self.existing_entries: dict[int, tuple[int, int]] = (\n {}\n ) # object ID => (offset, generation)\n self.new_entries: dict[int, tuple[int, int]] = (\n {}\n ) # object ID => (offset, generation)\n self.deleted_entries = {0: 65536} # object ID => generation\n self.reading_finished = False\n\n def __setitem__(self, key: int, value: tuple[int, int]) -> None:\n if self.reading_finished:\n self.new_entries[key] = value\n else:\n self.existing_entries[key] = value\n if key in self.deleted_entries:\n del self.deleted_entries[key]\n\n def __getitem__(self, key: int) -> tuple[int, int]:\n try:\n return self.new_entries[key]\n except KeyError:\n return self.existing_entries[key]\n\n def __delitem__(self, key: int) -> None:\n if key in self.new_entries:\n generation = self.new_entries[key][1] + 1\n del self.new_entries[key]\n self.deleted_entries[key] = generation\n elif key in self.existing_entries:\n generation = self.existing_entries[key][1] + 1\n self.deleted_entries[key] = generation\n elif key in self.deleted_entries:\n generation = self.deleted_entries[key]\n else:\n msg = f"object ID {key} cannot be deleted because it doesn't exist"\n raise IndexError(msg)\n\n def __contains__(self, key: int) -> bool:\n return key in self.existing_entries or key in self.new_entries\n\n def __len__(self) -> int:\n return len(\n set(self.existing_entries.keys())\n | set(self.new_entries.keys())\n | set(self.deleted_entries.keys())\n )\n\n def keys(self) -> set[int]:\n return (\n set(self.existing_entries.keys()) - set(self.deleted_entries.keys())\n ) | set(self.new_entries.keys())\n\n def write(self, f: IO[bytes]) -> int:\n keys = sorted(set(self.new_entries.keys()) | set(self.deleted_entries.keys()))\n deleted_keys = sorted(set(self.deleted_entries.keys()))\n startxref = f.tell()\n f.write(b"xref\n")\n while keys:\n # find a contiguous sequence of object IDs\n prev: int | None = None\n for index, key in enumerate(keys):\n if prev is None or prev + 1 == key:\n prev = key\n else:\n contiguous_keys = keys[:index]\n keys = keys[index:]\n break\n else:\n contiguous_keys = keys\n keys = []\n f.write(b"%d %d\n" % (contiguous_keys[0], len(contiguous_keys)))\n for object_id in contiguous_keys:\n if object_id in self.new_entries:\n f.write(b"%010d %05d n \n" % self.new_entries[object_id])\n else:\n this_deleted_object_id = deleted_keys.pop(0)\n check_format_condition(\n object_id == this_deleted_object_id,\n f"expected the next deleted object ID to be {object_id}, "\n f"instead found {this_deleted_object_id}",\n )\n try:\n next_in_linked_list = deleted_keys[0]\n except IndexError:\n next_in_linked_list = 0\n f.write(\n b"%010d %05d f \n"\n % (next_in_linked_list, self.deleted_entries[object_id])\n )\n return startxref\n\n\nclass PdfName:\n name: bytes\n\n def __init__(self, name: PdfName | bytes | str) -> None:\n if isinstance(name, PdfName):\n self.name = name.name\n elif isinstance(name, bytes):\n self.name = name\n else:\n self.name = name.encode("us-ascii")\n\n def name_as_str(self) -> str:\n return self.name.decode("us-ascii")\n\n def __eq__(self, other: object) -> bool:\n return (\n isinstance(other, PdfName) and other.name == self.name\n ) or other == self.name\n\n def __hash__(self) -> int:\n return hash(self.name)\n\n def __repr__(self) -> str:\n return f"{self.__class__.__name__}({repr(self.name)})"\n\n @classmethod\n def from_pdf_stream(cls, data: bytes) -> PdfName:\n return cls(PdfParser.interpret_name(data))\n\n allowed_chars = set(range(33, 127)) - {ord(c) for c in "#%/()<>[]{}"}\n\n def __bytes__(self) -> bytes:\n result = bytearray(b"/")\n for b in self.name:\n if b in self.allowed_chars:\n result.append(b)\n else:\n result.extend(b"#%02X" % b)\n return bytes(result)\n\n\nclass PdfArray(list[Any]):\n def __bytes__(self) -> bytes:\n return b"[ " + b" ".join(pdf_repr(x) for x in self) + b" ]"\n\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n _DictBase = collections.UserDict[Union[str, bytes], Any]\nelse:\n _DictBase = collections.UserDict\n\n\nclass PdfDict(_DictBase):\n def __setattr__(self, key: str, value: Any) -> None:\n if key == "data":\n collections.UserDict.__setattr__(self, key, value)\n else:\n self[key.encode("us-ascii")] = value\n\n def __getattr__(self, key: str) -> str | time.struct_time:\n try:\n value = self[key.encode("us-ascii")]\n except KeyError as e:\n raise AttributeError(key) from e\n if isinstance(value, bytes):\n value = decode_text(value)\n if key.endswith("Date"):\n if value.startswith("D:"):\n value = value[2:]\n\n relationship = "Z"\n if len(value) > 17:\n relationship = value[14]\n offset = int(value[15:17]) * 60\n if len(value) > 20:\n offset += int(value[18:20])\n\n format = "%Y%m%d%H%M%S"[: len(value) - 2]\n value = time.strptime(value[: len(format) + 2], format)\n if relationship in ["+", "-"]:\n offset *= 60\n if relationship == "+":\n offset *= -1\n value = time.gmtime(calendar.timegm(value) + offset)\n return value\n\n def __bytes__(self) -> bytes:\n out = bytearray(b"<<")\n for key, value in self.items():\n if value is None:\n continue\n value = pdf_repr(value)\n out.extend(b"\n")\n out.extend(bytes(PdfName(key)))\n out.extend(b" ")\n out.extend(value)\n out.extend(b"\n>>")\n return bytes(out)\n\n\nclass PdfBinary:\n def __init__(self, data: list[int] | bytes) -> None:\n self.data = data\n\n def __bytes__(self) -> bytes:\n return b"<%s>" % b"".join(b"%02X" % b for b in self.data)\n\n\nclass PdfStream:\n def __init__(self, dictionary: PdfDict, buf: bytes) -> None:\n self.dictionary = dictionary\n self.buf = buf\n\n def decode(self) -> bytes:\n try:\n filter = self.dictionary[b"Filter"]\n except KeyError:\n return self.buf\n if filter == b"FlateDecode":\n try:\n expected_length = self.dictionary[b"DL"]\n except KeyError:\n expected_length = self.dictionary[b"Length"]\n return zlib.decompress(self.buf, bufsize=int(expected_length))\n else:\n msg = f"stream filter {repr(filter)} unknown/unsupported"\n raise NotImplementedError(msg)\n\n\ndef pdf_repr(x: Any) -> bytes:\n if x is True:\n return b"true"\n elif x is False:\n return b"false"\n elif x is None:\n return b"null"\n elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):\n return bytes(x)\n elif isinstance(x, (int, float)):\n return str(x).encode("us-ascii")\n elif isinstance(x, time.struct_time):\n return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"\n elif isinstance(x, dict):\n return bytes(PdfDict(x))\n elif isinstance(x, list):\n return bytes(PdfArray(x))\n elif isinstance(x, str):\n return pdf_repr(encode_text(x))\n elif isinstance(x, bytes):\n # XXX escape more chars? handle binary garbage\n x = x.replace(b"\\", b"\\\\")\n x = x.replace(b"(", b"\\(")\n x = x.replace(b")", b"\\)")\n return b"(" + x + b")"\n else:\n return bytes(x)\n\n\nclass PdfParser:\n """Based on\n https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf\n Supports PDF up to 1.4\n """\n\n def __init__(\n self,\n filename: str | None = None,\n f: IO[bytes] | None = None,\n buf: bytes | bytearray | None = None,\n start_offset: int = 0,\n mode: str = "rb",\n ) -> None:\n if buf and f:\n msg = "specify buf or f or filename, but not both buf and f"\n raise RuntimeError(msg)\n self.filename = filename\n self.buf: bytes | bytearray | mmap.mmap | None = buf\n self.f = f\n self.start_offset = start_offset\n self.should_close_buf = False\n self.should_close_file = False\n if filename is not None and f is None:\n self.f = f = open(filename, mode)\n self.should_close_file = True\n if f is not None:\n self.buf = self.get_buf_from_file(f)\n self.should_close_buf = True\n if not filename and hasattr(f, "name"):\n self.filename = f.name\n self.cached_objects: dict[IndirectReference, Any] = {}\n self.root_ref: IndirectReference | None\n self.info_ref: IndirectReference | None\n self.pages_ref: IndirectReference | None\n self.last_xref_section_offset: int | None\n if self.buf:\n self.read_pdf_info()\n else:\n self.file_size_total = self.file_size_this = 0\n self.root = PdfDict()\n self.root_ref = None\n self.info = PdfDict()\n self.info_ref = None\n self.page_tree_root = PdfDict()\n self.pages: list[IndirectReference] = []\n self.orig_pages: list[IndirectReference] = []\n self.pages_ref = None\n self.last_xref_section_offset = None\n self.trailer_dict: dict[bytes, Any] = {}\n self.xref_table = XrefTable()\n self.xref_table.reading_finished = True\n if f:\n self.seek_end()\n\n def __enter__(self) -> PdfParser:\n return self\n\n def __exit__(self, *args: object) -> None:\n self.close()\n\n def start_writing(self) -> None:\n self.close_buf()\n self.seek_end()\n\n def close_buf(self) -> None:\n if isinstance(self.buf, mmap.mmap):\n self.buf.close()\n self.buf = None\n\n def close(self) -> None:\n if self.should_close_buf:\n self.close_buf()\n if self.f is not None and self.should_close_file:\n self.f.close()\n self.f = None\n\n def seek_end(self) -> None:\n assert self.f is not None\n self.f.seek(0, os.SEEK_END)\n\n def write_header(self) -> None:\n assert self.f is not None\n self.f.write(b"%PDF-1.4\n")\n\n def write_comment(self, s: str) -> None:\n assert self.f is not None\n self.f.write(f"% {s}\n".encode())\n\n def write_catalog(self) -> IndirectReference:\n assert self.f is not None\n self.del_root()\n self.root_ref = self.next_object_id(self.f.tell())\n self.pages_ref = self.next_object_id(0)\n self.rewrite_pages()\n self.write_obj(self.root_ref, Type=PdfName(b"Catalog"), Pages=self.pages_ref)\n self.write_obj(\n self.pages_ref,\n Type=PdfName(b"Pages"),\n Count=len(self.pages),\n Kids=self.pages,\n )\n return self.root_ref\n\n def rewrite_pages(self) -> None:\n pages_tree_nodes_to_delete = []\n for i, page_ref in enumerate(self.orig_pages):\n page_info = self.cached_objects[page_ref]\n del self.xref_table[page_ref.object_id]\n pages_tree_nodes_to_delete.append(page_info[PdfName(b"Parent")])\n if page_ref not in self.pages:\n # the page has been deleted\n continue\n # make dict keys into strings for passing to write_page\n stringified_page_info = {}\n for key, value in page_info.items():\n # key should be a PdfName\n stringified_page_info[key.name_as_str()] = value\n stringified_page_info["Parent"] = self.pages_ref\n new_page_ref = self.write_page(None, **stringified_page_info)\n for j, cur_page_ref in enumerate(self.pages):\n if cur_page_ref == page_ref:\n # replace the page reference with the new one\n self.pages[j] = new_page_ref\n # delete redundant Pages tree nodes from xref table\n for pages_tree_node_ref in pages_tree_nodes_to_delete:\n while pages_tree_node_ref:\n pages_tree_node = self.cached_objects[pages_tree_node_ref]\n if pages_tree_node_ref.object_id in self.xref_table:\n del self.xref_table[pages_tree_node_ref.object_id]\n pages_tree_node_ref = pages_tree_node.get(b"Parent", None)\n self.orig_pages = []\n\n def write_xref_and_trailer(\n self, new_root_ref: IndirectReference | None = None\n ) -> None:\n assert self.f is not None\n if new_root_ref:\n self.del_root()\n self.root_ref = new_root_ref\n if self.info:\n self.info_ref = self.write_obj(None, self.info)\n start_xref = self.xref_table.write(self.f)\n num_entries = len(self.xref_table)\n trailer_dict: dict[str | bytes, Any] = {\n b"Root": self.root_ref,\n b"Size": num_entries,\n }\n if self.last_xref_section_offset is not None:\n trailer_dict[b"Prev"] = self.last_xref_section_offset\n if self.info:\n trailer_dict[b"Info"] = self.info_ref\n self.last_xref_section_offset = start_xref\n self.f.write(\n b"trailer\n"\n + bytes(PdfDict(trailer_dict))\n + b"\nstartxref\n%d\n%%%%EOF" % start_xref\n )\n\n def write_page(\n self, ref: int | IndirectReference | None, *objs: Any, **dict_obj: Any\n ) -> IndirectReference:\n obj_ref = self.pages[ref] if isinstance(ref, int) else ref\n if "Type" not in dict_obj:\n dict_obj["Type"] = PdfName(b"Page")\n if "Parent" not in dict_obj:\n dict_obj["Parent"] = self.pages_ref\n return self.write_obj(obj_ref, *objs, **dict_obj)\n\n def write_obj(\n self, ref: IndirectReference | None, *objs: Any, **dict_obj: Any\n ) -> IndirectReference:\n assert self.f is not None\n f = self.f\n if ref is None:\n ref = self.next_object_id(f.tell())\n else:\n self.xref_table[ref.object_id] = (f.tell(), ref.generation)\n f.write(bytes(IndirectObjectDef(*ref)))\n stream = dict_obj.pop("stream", None)\n if stream is not None:\n dict_obj["Length"] = len(stream)\n if dict_obj:\n f.write(pdf_repr(dict_obj))\n for obj in objs:\n f.write(pdf_repr(obj))\n if stream is not None:\n f.write(b"stream\n")\n f.write(stream)\n f.write(b"\nendstream\n")\n f.write(b"endobj\n")\n return ref\n\n def del_root(self) -> None:\n if self.root_ref is None:\n return\n del self.xref_table[self.root_ref.object_id]\n del self.xref_table[self.root[b"Pages"].object_id]\n\n @staticmethod\n def get_buf_from_file(f: IO[bytes]) -> bytes | mmap.mmap:\n if hasattr(f, "getbuffer"):\n return f.getbuffer()\n elif hasattr(f, "getvalue"):\n return f.getvalue()\n else:\n try:\n return mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n except ValueError: # cannot mmap an empty file\n return b""\n\n def read_pdf_info(self) -> None:\n assert self.buf is not None\n self.file_size_total = len(self.buf)\n self.file_size_this = self.file_size_total - self.start_offset\n self.read_trailer()\n check_format_condition(\n self.trailer_dict.get(b"Root") is not None, "Root is missing"\n )\n self.root_ref = self.trailer_dict[b"Root"]\n assert self.root_ref is not None\n self.info_ref = self.trailer_dict.get(b"Info", None)\n self.root = PdfDict(self.read_indirect(self.root_ref))\n if self.info_ref is None:\n self.info = PdfDict()\n else:\n self.info = PdfDict(self.read_indirect(self.info_ref))\n check_format_condition(b"Type" in self.root, "/Type missing in Root")\n check_format_condition(\n self.root[b"Type"] == b"Catalog", "/Type in Root is not /Catalog"\n )\n check_format_condition(\n self.root.get(b"Pages") is not None, "/Pages missing in Root"\n )\n check_format_condition(\n isinstance(self.root[b"Pages"], IndirectReference),\n "/Pages in Root is not an indirect reference",\n )\n self.pages_ref = self.root[b"Pages"]\n assert self.pages_ref is not None\n self.page_tree_root = self.read_indirect(self.pages_ref)\n self.pages = self.linearize_page_tree(self.page_tree_root)\n # save the original list of page references\n # in case the user modifies, adds or deletes some pages\n # and we need to rewrite the pages and their list\n self.orig_pages = self.pages[:]\n\n def next_object_id(self, offset: int | None = None) -> IndirectReference:\n try:\n # TODO: support reuse of deleted objects\n reference = IndirectReference(max(self.xref_table.keys()) + 1, 0)\n except ValueError:\n reference = IndirectReference(1, 0)\n if offset is not None:\n self.xref_table[reference.object_id] = (offset, 0)\n return reference\n\n delimiter = rb"[][()<>{}/%]"\n delimiter_or_ws = rb"[][()<>{}/%\000\011\012\014\015\040]"\n whitespace = rb"[\000\011\012\014\015\040]"\n whitespace_or_hex = rb"[\000\011\012\014\015\0400-9a-fA-F]"\n whitespace_optional = whitespace + b"*"\n whitespace_mandatory = whitespace + b"+"\n # No "\012" aka "\n" or "\015" aka "\r":\n whitespace_optional_no_nl = rb"[\000\011\014\040]*"\n newline_only = rb"[\r\n]+"\n newline = whitespace_optional_no_nl + newline_only + whitespace_optional_no_nl\n re_trailer_end = re.compile(\n whitespace_mandatory\n + rb"trailer"\n + whitespace_optional\n + rb"<<(.*>>)"\n + newline\n + rb"startxref"\n + newline\n + rb"([0-9]+)"\n + newline\n + rb"%%EOF"\n + whitespace_optional\n + rb"$",\n re.DOTALL,\n )\n re_trailer_prev = re.compile(\n whitespace_optional\n + rb"trailer"\n + whitespace_optional\n + rb"<<(.*?>>)"\n + newline\n + rb"startxref"\n + newline\n + rb"([0-9]+)"\n + newline\n + rb"%%EOF"\n + whitespace_optional,\n re.DOTALL,\n )\n\n def read_trailer(self) -> None:\n assert self.buf is not None\n search_start_offset = len(self.buf) - 16384\n if search_start_offset < self.start_offset:\n search_start_offset = self.start_offset\n m = self.re_trailer_end.search(self.buf, search_start_offset)\n check_format_condition(m is not None, "trailer end not found")\n # make sure we found the LAST trailer\n last_match = m\n while m:\n last_match = m\n m = self.re_trailer_end.search(self.buf, m.start() + 16)\n if not m:\n m = last_match\n assert m is not None\n trailer_data = m.group(1)\n self.last_xref_section_offset = int(m.group(2))\n self.trailer_dict = self.interpret_trailer(trailer_data)\n self.xref_table = XrefTable()\n self.read_xref_table(xref_section_offset=self.last_xref_section_offset)\n if b"Prev" in self.trailer_dict:\n self.read_prev_trailer(self.trailer_dict[b"Prev"])\n\n def read_prev_trailer(self, xref_section_offset: int) -> None:\n assert self.buf is not None\n trailer_offset = self.read_xref_table(xref_section_offset=xref_section_offset)\n m = self.re_trailer_prev.search(\n self.buf[trailer_offset : trailer_offset + 16384]\n )\n check_format_condition(m is not None, "previous trailer not found")\n assert m is not None\n trailer_data = m.group(1)\n check_format_condition(\n int(m.group(2)) == xref_section_offset,\n "xref section offset in previous trailer doesn't match what was expected",\n )\n trailer_dict = self.interpret_trailer(trailer_data)\n if b"Prev" in trailer_dict:\n self.read_prev_trailer(trailer_dict[b"Prev"])\n\n re_whitespace_optional = re.compile(whitespace_optional)\n re_name = re.compile(\n whitespace_optional\n + rb"/([!-$&'*-.0-;=?-Z\\^-z|~]+)(?="\n + delimiter_or_ws\n + rb")"\n )\n re_dict_start = re.compile(whitespace_optional + rb"<<")\n re_dict_end = re.compile(whitespace_optional + rb">>" + whitespace_optional)\n\n @classmethod\n def interpret_trailer(cls, trailer_data: bytes) -> dict[bytes, Any]:\n trailer = {}\n offset = 0\n while True:\n m = cls.re_name.match(trailer_data, offset)\n if not m:\n m = cls.re_dict_end.match(trailer_data, offset)\n check_format_condition(\n m is not None and m.end() == len(trailer_data),\n "name not found in trailer, remaining data: "\n + repr(trailer_data[offset:]),\n )\n break\n key = cls.interpret_name(m.group(1))\n assert isinstance(key, bytes)\n value, value_offset = cls.get_value(trailer_data, m.end())\n trailer[key] = value\n if value_offset is None:\n break\n offset = value_offset\n check_format_condition(\n b"Size" in trailer and isinstance(trailer[b"Size"], int),\n "/Size not in trailer or not an integer",\n )\n check_format_condition(\n b"Root" in trailer and isinstance(trailer[b"Root"], IndirectReference),\n "/Root not in trailer or not an indirect reference",\n )\n return trailer\n\n re_hashes_in_name = re.compile(rb"([^#]*)(#([0-9a-fA-F]{2}))?")\n\n @classmethod\n def interpret_name(cls, raw: bytes, as_text: bool = False) -> str | bytes:\n name = b""\n for m in cls.re_hashes_in_name.finditer(raw):\n if m.group(3):\n name += m.group(1) + bytearray.fromhex(m.group(3).decode("us-ascii"))\n else:\n name += m.group(1)\n if as_text:\n return name.decode("utf-8")\n else:\n return bytes(name)\n\n re_null = re.compile(whitespace_optional + rb"null(?=" + delimiter_or_ws + rb")")\n re_true = re.compile(whitespace_optional + rb"true(?=" + delimiter_or_ws + rb")")\n re_false = re.compile(whitespace_optional + rb"false(?=" + delimiter_or_ws + rb")")\n re_int = re.compile(\n whitespace_optional + rb"([-+]?[0-9]+)(?=" + delimiter_or_ws + rb")"\n )\n re_real = re.compile(\n whitespace_optional\n + rb"([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+))(?="\n + delimiter_or_ws\n + rb")"\n )\n re_array_start = re.compile(whitespace_optional + rb"\[")\n re_array_end = re.compile(whitespace_optional + rb"]")\n re_string_hex = re.compile(\n whitespace_optional + rb"<(" + whitespace_or_hex + rb"*)>"\n )\n re_string_lit = re.compile(whitespace_optional + rb"\(")\n re_indirect_reference = re.compile(\n whitespace_optional\n + rb"([-+]?[0-9]+)"\n + whitespace_mandatory\n + rb"([-+]?[0-9]+)"\n + whitespace_mandatory\n + rb"R(?="\n + delimiter_or_ws\n + rb")"\n )\n re_indirect_def_start = re.compile(\n whitespace_optional\n + rb"([-+]?[0-9]+)"\n + whitespace_mandatory\n + rb"([-+]?[0-9]+)"\n + whitespace_mandatory\n + rb"obj(?="\n + delimiter_or_ws\n + rb")"\n )\n re_indirect_def_end = re.compile(\n whitespace_optional + rb"endobj(?=" + delimiter_or_ws + rb")"\n )\n re_comment = re.compile(\n rb"(" + whitespace_optional + rb"%[^\r\n]*" + newline + rb")*"\n )\n re_stream_start = re.compile(whitespace_optional + rb"stream\r?\n")\n re_stream_end = re.compile(\n whitespace_optional + rb"endstream(?=" + delimiter_or_ws + rb")"\n )\n\n @classmethod\n def get_value(\n cls,\n data: bytes | bytearray | mmap.mmap,\n offset: int,\n expect_indirect: IndirectReference | None = None,\n max_nesting: int = -1,\n ) -> tuple[Any, int | None]:\n if max_nesting == 0:\n return None, None\n m = cls.re_comment.match(data, offset)\n if m:\n offset = m.end()\n m = cls.re_indirect_def_start.match(data, offset)\n if m:\n check_format_condition(\n int(m.group(1)) > 0,\n "indirect object definition: object ID must be greater than 0",\n )\n check_format_condition(\n int(m.group(2)) >= 0,\n "indirect object definition: generation must be non-negative",\n )\n check_format_condition(\n expect_indirect is None\n or expect_indirect\n == IndirectReference(int(m.group(1)), int(m.group(2))),\n "indirect object definition different than expected",\n )\n object, object_offset = cls.get_value(\n data, m.end(), max_nesting=max_nesting - 1\n )\n if object_offset is None:\n return object, None\n m = cls.re_indirect_def_end.match(data, object_offset)\n check_format_condition(\n m is not None, "indirect object definition end not found"\n )\n assert m is not None\n return object, m.end()\n check_format_condition(\n not expect_indirect, "indirect object definition not found"\n )\n m = cls.re_indirect_reference.match(data, offset)\n if m:\n check_format_condition(\n int(m.group(1)) > 0,\n "indirect object reference: object ID must be greater than 0",\n )\n check_format_condition(\n int(m.group(2)) >= 0,\n "indirect object reference: generation must be non-negative",\n )\n return IndirectReference(int(m.group(1)), int(m.group(2))), m.end()\n m = cls.re_dict_start.match(data, offset)\n if m:\n offset = m.end()\n result: dict[Any, Any] = {}\n m = cls.re_dict_end.match(data, offset)\n current_offset: int | None = offset\n while not m:\n assert current_offset is not None\n key, current_offset = cls.get_value(\n data, current_offset, max_nesting=max_nesting - 1\n )\n if current_offset is None:\n return result, None\n value, current_offset = cls.get_value(\n data, current_offset, max_nesting=max_nesting - 1\n )\n result[key] = value\n if current_offset is None:\n return result, None\n m = cls.re_dict_end.match(data, current_offset)\n current_offset = m.end()\n m = cls.re_stream_start.match(data, current_offset)\n if m:\n stream_len = result.get(b"Length")\n if stream_len is None or not isinstance(stream_len, int):\n msg = f"bad or missing Length in stream dict ({stream_len})"\n raise PdfFormatError(msg)\n stream_data = data[m.end() : m.end() + stream_len]\n m = cls.re_stream_end.match(data, m.end() + stream_len)\n check_format_condition(m is not None, "stream end not found")\n assert m is not None\n current_offset = m.end()\n return PdfStream(PdfDict(result), stream_data), current_offset\n return PdfDict(result), current_offset\n m = cls.re_array_start.match(data, offset)\n if m:\n offset = m.end()\n results = []\n m = cls.re_array_end.match(data, offset)\n current_offset = offset\n while not m:\n assert current_offset is not None\n value, current_offset = cls.get_value(\n data, current_offset, max_nesting=max_nesting - 1\n )\n results.append(value)\n if current_offset is None:\n return results, None\n m = cls.re_array_end.match(data, current_offset)\n return results, m.end()\n m = cls.re_null.match(data, offset)\n if m:\n return None, m.end()\n m = cls.re_true.match(data, offset)\n if m:\n return True, m.end()\n m = cls.re_false.match(data, offset)\n if m:\n return False, m.end()\n m = cls.re_name.match(data, offset)\n if m:\n return PdfName(cls.interpret_name(m.group(1))), m.end()\n m = cls.re_int.match(data, offset)\n if m:\n return int(m.group(1)), m.end()\n m = cls.re_real.match(data, offset)\n if m:\n # XXX Decimal instead of float???\n return float(m.group(1)), m.end()\n m = cls.re_string_hex.match(data, offset)\n if m:\n # filter out whitespace\n hex_string = bytearray(\n b for b in m.group(1) if b in b"0123456789abcdefABCDEF"\n )\n if len(hex_string) % 2 == 1:\n # append a 0 if the length is not even - yes, at the end\n hex_string.append(ord(b"0"))\n return bytearray.fromhex(hex_string.decode("us-ascii")), m.end()\n m = cls.re_string_lit.match(data, offset)\n if m:\n return cls.get_literal_string(data, m.end())\n # return None, offset # fallback (only for debugging)\n msg = f"unrecognized object: {repr(data[offset : offset + 32])}"\n raise PdfFormatError(msg)\n\n re_lit_str_token = re.compile(\n rb"(\\[nrtbf()\\])|(\\[0-9]{1,3})|(\\(\r\n|\r|\n))|(\r\n|\r|\n)|(\()|(\))"\n )\n escaped_chars = {\n b"n": b"\n",\n b"r": b"\r",\n b"t": b"\t",\n b"b": b"\b",\n b"f": b"\f",\n b"(": b"(",\n b")": b")",\n b"\\": b"\\",\n ord(b"n"): b"\n",\n ord(b"r"): b"\r",\n ord(b"t"): b"\t",\n ord(b"b"): b"\b",\n ord(b"f"): b"\f",\n ord(b"("): b"(",\n ord(b")"): b")",\n ord(b"\\"): b"\\",\n }\n\n @classmethod\n def get_literal_string(\n cls, data: bytes | bytearray | mmap.mmap, offset: int\n ) -> tuple[bytes, int]:\n nesting_depth = 0\n result = bytearray()\n for m in cls.re_lit_str_token.finditer(data, offset):\n result.extend(data[offset : m.start()])\n if m.group(1):\n result.extend(cls.escaped_chars[m.group(1)[1]])\n elif m.group(2):\n result.append(int(m.group(2)[1:], 8))\n elif m.group(3):\n pass\n elif m.group(5):\n result.extend(b"\n")\n elif m.group(6):\n result.extend(b"(")\n nesting_depth += 1\n elif m.group(7):\n if nesting_depth == 0:\n return bytes(result), m.end()\n result.extend(b")")\n nesting_depth -= 1\n offset = m.end()\n msg = "unfinished literal string"\n raise PdfFormatError(msg)\n\n re_xref_section_start = re.compile(whitespace_optional + rb"xref" + newline)\n re_xref_subsection_start = re.compile(\n whitespace_optional\n + rb"([0-9]+)"\n + whitespace_mandatory\n + rb"([0-9]+)"\n + whitespace_optional\n + newline_only\n )\n re_xref_entry = re.compile(rb"([0-9]{10}) ([0-9]{5}) ([fn])( \r| \n|\r\n)")\n\n def read_xref_table(self, xref_section_offset: int) -> int:\n assert self.buf is not None\n subsection_found = False\n m = self.re_xref_section_start.match(\n self.buf, xref_section_offset + self.start_offset\n )\n check_format_condition(m is not None, "xref section start not found")\n assert m is not None\n offset = m.end()\n while True:\n m = self.re_xref_subsection_start.match(self.buf, offset)\n if not m:\n check_format_condition(\n subsection_found, "xref subsection start not found"\n )\n break\n subsection_found = True\n offset = m.end()\n first_object = int(m.group(1))\n num_objects = int(m.group(2))\n for i in range(first_object, first_object + num_objects):\n m = self.re_xref_entry.match(self.buf, offset)\n check_format_condition(m is not None, "xref entry not found")\n assert m is not None\n offset = m.end()\n is_free = m.group(3) == b"f"\n if not is_free:\n generation = int(m.group(2))\n new_entry = (int(m.group(1)), generation)\n if i not in self.xref_table:\n self.xref_table[i] = new_entry\n return offset\n\n def read_indirect(self, ref: IndirectReference, max_nesting: int = -1) -> Any:\n offset, generation = self.xref_table[ref[0]]\n check_format_condition(\n generation == ref[1],\n f"expected to find generation {ref[1]} for object ID {ref[0]} in xref "\n f"table, instead found generation {generation} at offset {offset}",\n )\n assert self.buf is not None\n value = self.get_value(\n self.buf,\n offset + self.start_offset,\n expect_indirect=IndirectReference(*ref),\n max_nesting=max_nesting,\n )[0]\n self.cached_objects[ref] = value\n return value\n\n def linearize_page_tree(\n self, node: PdfDict | None = None\n ) -> list[IndirectReference]:\n page_node = node if node is not None else self.page_tree_root\n check_format_condition(\n page_node[b"Type"] == b"Pages", "/Type of page tree node is not /Pages"\n )\n pages = []\n for kid in page_node[b"Kids"]:\n kid_object = self.read_indirect(kid)\n if kid_object[b"Type"] == b"Page":\n pages.append(kid)\n else:\n pages.extend(self.linearize_page_tree(node=kid_object))\n return pages\n | .venv\Lib\site-packages\PIL\PdfParser.py | PdfParser.py | Python | 39,061 | 0.95 | 0.179702 | 0.019388 | node-utils | 349 | 2023-11-24T08:59:50.044430 | MIT | false | a84ff0614dfa77ba6c470e939457414c |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PIXAR raster support for PIL\n#\n# history:\n# 97-01-29 fl Created\n#\n# notes:\n# This is incomplete; it is based on a few samples created with\n# Photoshop 2.5 and 3.0, and a summary description provided by\n# Greg Coats <gcoats@labiris.er.usgs.gov>. Hopefully, "L" and\n# "RGBA" support will be added in future versions.\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1997.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFile\nfrom ._binary import i16le as i16\n\n#\n# helpers\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"\200\350\000\000")\n\n\n##\n# Image plugin for PIXAR raster images.\n\n\nclass PixarImageFile(ImageFile.ImageFile):\n format = "PIXAR"\n format_description = "PIXAR raster image"\n\n def _open(self) -> None:\n # assuming a 4-byte magic label\n assert self.fp is not None\n\n s = self.fp.read(4)\n if not _accept(s):\n msg = "not a PIXAR file"\n raise SyntaxError(msg)\n\n # read rest of header\n s = s + self.fp.read(508)\n\n self._size = i16(s, 418), i16(s, 416)\n\n # get channel/depth descriptions\n mode = i16(s, 424), i16(s, 426)\n\n if mode == (14, 2):\n self._mode = "RGB"\n # FIXME: to be continued...\n\n # create tile descriptor (assuming "dumped")\n self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 1024, self.mode)]\n\n\n#\n# --------------------------------------------------------------------\n\nImage.register_open(PixarImageFile.format, PixarImageFile, _accept)\n\nImage.register_extension(PixarImageFile.format, ".pxr")\n | .venv\Lib\site-packages\PIL\PixarImagePlugin.py | PixarImagePlugin.py | Python | 1,830 | 0.95 | 0.111111 | 0.584906 | awesome-app | 960 | 2024-04-29T13:30:11.291403 | MIT | false | aedc60654ce0e45ca957a03c02d274b7 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PNG support code\n#\n# See "PNG (Portable Network Graphics) Specification, version 1.0;\n# W3C Recommendation", 1996-10-01, Thomas Boutell (ed.).\n#\n# history:\n# 1996-05-06 fl Created (couldn't resist it)\n# 1996-12-14 fl Upgraded, added read and verify support (0.2)\n# 1996-12-15 fl Separate PNG stream parser\n# 1996-12-29 fl Added write support, added getchunks\n# 1996-12-30 fl Eliminated circular references in decoder (0.3)\n# 1998-07-12 fl Read/write 16-bit images as mode I (0.4)\n# 2001-02-08 fl Added transparency support (from Zircon) (0.5)\n# 2001-04-16 fl Don't close data source in "open" method (0.6)\n# 2004-02-24 fl Don't even pretend to support interlaced files (0.7)\n# 2004-08-31 fl Do basic sanity check on chunk identifiers (0.8)\n# 2004-09-20 fl Added PngInfo chunk container\n# 2004-12-18 fl Added DPI read support (based on code by Niki Spahiev)\n# 2008-08-13 fl Added tRNS support for RGB images\n# 2009-03-06 fl Support for preserving ICC profiles (by Florian Hoech)\n# 2009-03-08 fl Added zTXT support (from Lowell Alleman)\n# 2009-03-29 fl Read interlaced PNG files (from Conrado Porto Lopes Gouvua)\n#\n# Copyright (c) 1997-2009 by Secret Labs AB\n# Copyright (c) 1996 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport itertools\nimport logging\nimport re\nimport struct\nimport warnings\nimport zlib\nfrom collections.abc import Callable\nfrom enum import IntEnum\nfrom typing import IO, Any, NamedTuple, NoReturn, cast\n\nfrom . import Image, ImageChops, ImageFile, ImagePalette, ImageSequence\nfrom ._binary import i16be as i16\nfrom ._binary import i32be as i32\nfrom ._binary import o8\nfrom ._binary import o16be as o16\nfrom ._binary import o32be as o32\nfrom ._deprecate import deprecate\nfrom ._util import DeferredError\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from . import _imaging\n\nlogger = logging.getLogger(__name__)\n\nis_cid = re.compile(rb"\w\w\w\w").match\n\n\n_MAGIC = b"\211PNG\r\n\032\n"\n\n\n_MODES = {\n # supported bits/color combinations, and corresponding modes/rawmodes\n # Grayscale\n (1, 0): ("1", "1"),\n (2, 0): ("L", "L;2"),\n (4, 0): ("L", "L;4"),\n (8, 0): ("L", "L"),\n (16, 0): ("I;16", "I;16B"),\n # Truecolour\n (8, 2): ("RGB", "RGB"),\n (16, 2): ("RGB", "RGB;16B"),\n # Indexed-colour\n (1, 3): ("P", "P;1"),\n (2, 3): ("P", "P;2"),\n (4, 3): ("P", "P;4"),\n (8, 3): ("P", "P"),\n # Grayscale with alpha\n (8, 4): ("LA", "LA"),\n (16, 4): ("RGBA", "LA;16B"), # LA;16B->LA not yet available\n # Truecolour with alpha\n (8, 6): ("RGBA", "RGBA"),\n (16, 6): ("RGBA", "RGBA;16B"),\n}\n\n\n_simple_palette = re.compile(b"^\xff*\x00\xff*$")\n\nMAX_TEXT_CHUNK = ImageFile.SAFEBLOCK\n"""\nMaximum decompressed size for a iTXt or zTXt chunk.\nEliminates decompression bombs where compressed chunks can expand 1000x.\nSee :ref:`Text in PNG File Format<png-text>`.\n"""\nMAX_TEXT_MEMORY = 64 * MAX_TEXT_CHUNK\n"""\nSet the maximum total text chunk size.\nSee :ref:`Text in PNG File Format<png-text>`.\n"""\n\n\n# APNG frame disposal modes\nclass Disposal(IntEnum):\n OP_NONE = 0\n """\n No disposal is done on this frame before rendering the next frame.\n See :ref:`Saving APNG sequences<apng-saving>`.\n """\n OP_BACKGROUND = 1\n """\n This frame’s modified region is cleared to fully transparent black before rendering\n the next frame.\n See :ref:`Saving APNG sequences<apng-saving>`.\n """\n OP_PREVIOUS = 2\n """\n This frame’s modified region is reverted to the previous frame’s contents before\n rendering the next frame.\n See :ref:`Saving APNG sequences<apng-saving>`.\n """\n\n\n# APNG frame blend modes\nclass Blend(IntEnum):\n OP_SOURCE = 0\n """\n All color components of this frame, including alpha, overwrite the previous output\n image contents.\n See :ref:`Saving APNG sequences<apng-saving>`.\n """\n OP_OVER = 1\n """\n This frame should be alpha composited with the previous output image contents.\n See :ref:`Saving APNG sequences<apng-saving>`.\n """\n\n\ndef _safe_zlib_decompress(s: bytes) -> bytes:\n dobj = zlib.decompressobj()\n plaintext = dobj.decompress(s, MAX_TEXT_CHUNK)\n if dobj.unconsumed_tail:\n msg = "Decompressed data too large for PngImagePlugin.MAX_TEXT_CHUNK"\n raise ValueError(msg)\n return plaintext\n\n\ndef _crc32(data: bytes, seed: int = 0) -> int:\n return zlib.crc32(data, seed) & 0xFFFFFFFF\n\n\n# --------------------------------------------------------------------\n# Support classes. Suitable for PNG and related formats like MNG etc.\n\n\nclass ChunkStream:\n def __init__(self, fp: IO[bytes]) -> None:\n self.fp: IO[bytes] | None = fp\n self.queue: list[tuple[bytes, int, int]] | None = []\n\n def read(self) -> tuple[bytes, int, int]:\n """Fetch a new chunk. Returns header information."""\n cid = None\n\n assert self.fp is not None\n if self.queue:\n cid, pos, length = self.queue.pop()\n self.fp.seek(pos)\n else:\n s = self.fp.read(8)\n cid = s[4:]\n pos = self.fp.tell()\n length = i32(s)\n\n if not is_cid(cid):\n if not ImageFile.LOAD_TRUNCATED_IMAGES:\n msg = f"broken PNG file (chunk {repr(cid)})"\n raise SyntaxError(msg)\n\n return cid, pos, length\n\n def __enter__(self) -> ChunkStream:\n return self\n\n def __exit__(self, *args: object) -> None:\n self.close()\n\n def close(self) -> None:\n self.queue = self.fp = None\n\n def push(self, cid: bytes, pos: int, length: int) -> None:\n assert self.queue is not None\n self.queue.append((cid, pos, length))\n\n def call(self, cid: bytes, pos: int, length: int) -> bytes:\n """Call the appropriate chunk handler"""\n\n logger.debug("STREAM %r %s %s", cid, pos, length)\n return getattr(self, f"chunk_{cid.decode('ascii')}")(pos, length)\n\n def crc(self, cid: bytes, data: bytes) -> None:\n """Read and verify checksum"""\n\n # Skip CRC checks for ancillary chunks if allowed to load truncated\n # images\n # 5th byte of first char is 1 [specs, section 5.4]\n if ImageFile.LOAD_TRUNCATED_IMAGES and (cid[0] >> 5 & 1):\n self.crc_skip(cid, data)\n return\n\n assert self.fp is not None\n try:\n crc1 = _crc32(data, _crc32(cid))\n crc2 = i32(self.fp.read(4))\n if crc1 != crc2:\n msg = f"broken PNG file (bad header checksum in {repr(cid)})"\n raise SyntaxError(msg)\n except struct.error as e:\n msg = f"broken PNG file (incomplete checksum in {repr(cid)})"\n raise SyntaxError(msg) from e\n\n def crc_skip(self, cid: bytes, data: bytes) -> None:\n """Read checksum"""\n\n assert self.fp is not None\n self.fp.read(4)\n\n def verify(self, endchunk: bytes = b"IEND") -> list[bytes]:\n # Simple approach; just calculate checksum for all remaining\n # blocks. Must be called directly after open.\n\n cids = []\n\n assert self.fp is not None\n while True:\n try:\n cid, pos, length = self.read()\n except struct.error as e:\n msg = "truncated PNG file"\n raise OSError(msg) from e\n\n if cid == endchunk:\n break\n self.crc(cid, ImageFile._safe_read(self.fp, length))\n cids.append(cid)\n\n return cids\n\n\nclass iTXt(str):\n """\n Subclass of string to allow iTXt chunks to look like strings while\n keeping their extra information\n\n """\n\n lang: str | bytes | None\n tkey: str | bytes | None\n\n @staticmethod\n def __new__(\n cls, text: str, lang: str | None = None, tkey: str | None = None\n ) -> iTXt:\n """\n :param cls: the class to use when creating the instance\n :param text: value for this key\n :param lang: language code\n :param tkey: UTF-8 version of the key name\n """\n\n self = str.__new__(cls, text)\n self.lang = lang\n self.tkey = tkey\n return self\n\n\nclass PngInfo:\n """\n PNG chunk container (for use with save(pnginfo=))\n\n """\n\n def __init__(self) -> None:\n self.chunks: list[tuple[bytes, bytes, bool]] = []\n\n def add(self, cid: bytes, data: bytes, after_idat: bool = False) -> None:\n """Appends an arbitrary chunk. Use with caution.\n\n :param cid: a byte string, 4 bytes long.\n :param data: a byte string of the encoded data\n :param after_idat: for use with private chunks. Whether the chunk\n should be written after IDAT\n\n """\n\n self.chunks.append((cid, data, after_idat))\n\n def add_itxt(\n self,\n key: str | bytes,\n value: str | bytes,\n lang: str | bytes = "",\n tkey: str | bytes = "",\n zip: bool = False,\n ) -> None:\n """Appends an iTXt chunk.\n\n :param key: latin-1 encodable text key name\n :param value: value for this key\n :param lang: language code\n :param tkey: UTF-8 version of the key name\n :param zip: compression flag\n\n """\n\n if not isinstance(key, bytes):\n key = key.encode("latin-1", "strict")\n if not isinstance(value, bytes):\n value = value.encode("utf-8", "strict")\n if not isinstance(lang, bytes):\n lang = lang.encode("utf-8", "strict")\n if not isinstance(tkey, bytes):\n tkey = tkey.encode("utf-8", "strict")\n\n if zip:\n self.add(\n b"iTXt",\n key + b"\0\x01\0" + lang + b"\0" + tkey + b"\0" + zlib.compress(value),\n )\n else:\n self.add(b"iTXt", key + b"\0\0\0" + lang + b"\0" + tkey + b"\0" + value)\n\n def add_text(\n self, key: str | bytes, value: str | bytes | iTXt, zip: bool = False\n ) -> None:\n """Appends a text chunk.\n\n :param key: latin-1 encodable text key name\n :param value: value for this key, text or an\n :py:class:`PIL.PngImagePlugin.iTXt` instance\n :param zip: compression flag\n\n """\n if isinstance(value, iTXt):\n return self.add_itxt(\n key,\n value,\n value.lang if value.lang is not None else b"",\n value.tkey if value.tkey is not None else b"",\n zip=zip,\n )\n\n # The tEXt chunk stores latin-1 text\n if not isinstance(value, bytes):\n try:\n value = value.encode("latin-1", "strict")\n except UnicodeError:\n return self.add_itxt(key, value, zip=zip)\n\n if not isinstance(key, bytes):\n key = key.encode("latin-1", "strict")\n\n if zip:\n self.add(b"zTXt", key + b"\0\0" + zlib.compress(value))\n else:\n self.add(b"tEXt", key + b"\0" + value)\n\n\n# --------------------------------------------------------------------\n# PNG image stream (IHDR/IEND)\n\n\nclass _RewindState(NamedTuple):\n info: dict[str | tuple[int, int], Any]\n tile: list[ImageFile._Tile]\n seq_num: int | None\n\n\nclass PngStream(ChunkStream):\n def __init__(self, fp: IO[bytes]) -> None:\n super().__init__(fp)\n\n # local copies of Image attributes\n self.im_info: dict[str | tuple[int, int], Any] = {}\n self.im_text: dict[str, str | iTXt] = {}\n self.im_size = (0, 0)\n self.im_mode = ""\n self.im_tile: list[ImageFile._Tile] = []\n self.im_palette: tuple[str, bytes] | None = None\n self.im_custom_mimetype: str | None = None\n self.im_n_frames: int | None = None\n self._seq_num: int | None = None\n self.rewind_state = _RewindState({}, [], None)\n\n self.text_memory = 0\n\n def check_text_memory(self, chunklen: int) -> None:\n self.text_memory += chunklen\n if self.text_memory > MAX_TEXT_MEMORY:\n msg = (\n "Too much memory used in text chunks: "\n f"{self.text_memory}>MAX_TEXT_MEMORY"\n )\n raise ValueError(msg)\n\n def save_rewind(self) -> None:\n self.rewind_state = _RewindState(\n self.im_info.copy(),\n self.im_tile,\n self._seq_num,\n )\n\n def rewind(self) -> None:\n self.im_info = self.rewind_state.info.copy()\n self.im_tile = self.rewind_state.tile\n self._seq_num = self.rewind_state.seq_num\n\n def chunk_iCCP(self, pos: int, length: int) -> bytes:\n # ICC profile\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n # according to PNG spec, the iCCP chunk contains:\n # Profile name 1-79 bytes (character string)\n # Null separator 1 byte (null character)\n # Compression method 1 byte (0)\n # Compressed profile n bytes (zlib with deflate compression)\n i = s.find(b"\0")\n logger.debug("iCCP profile name %r", s[:i])\n comp_method = s[i + 1]\n logger.debug("Compression method %s", comp_method)\n if comp_method != 0:\n msg = f"Unknown compression method {comp_method} in iCCP chunk"\n raise SyntaxError(msg)\n try:\n icc_profile = _safe_zlib_decompress(s[i + 2 :])\n except ValueError:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n icc_profile = None\n else:\n raise\n except zlib.error:\n icc_profile = None # FIXME\n self.im_info["icc_profile"] = icc_profile\n return s\n\n def chunk_IHDR(self, pos: int, length: int) -> bytes:\n # image header\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if length < 13:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n msg = "Truncated IHDR chunk"\n raise ValueError(msg)\n self.im_size = i32(s, 0), i32(s, 4)\n try:\n self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]\n except Exception:\n pass\n if s[12]:\n self.im_info["interlace"] = 1\n if s[11]:\n msg = "unknown filter category"\n raise SyntaxError(msg)\n return s\n\n def chunk_IDAT(self, pos: int, length: int) -> NoReturn:\n # image data\n if "bbox" in self.im_info:\n tile = [ImageFile._Tile("zip", self.im_info["bbox"], pos, self.im_rawmode)]\n else:\n if self.im_n_frames is not None:\n self.im_info["default_image"] = True\n tile = [ImageFile._Tile("zip", (0, 0) + self.im_size, pos, self.im_rawmode)]\n self.im_tile = tile\n self.im_idat = length\n msg = "image data found"\n raise EOFError(msg)\n\n def chunk_IEND(self, pos: int, length: int) -> NoReturn:\n msg = "end of PNG image"\n raise EOFError(msg)\n\n def chunk_PLTE(self, pos: int, length: int) -> bytes:\n # palette\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if self.im_mode == "P":\n self.im_palette = "RGB", s\n return s\n\n def chunk_tRNS(self, pos: int, length: int) -> bytes:\n # transparency\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if self.im_mode == "P":\n if _simple_palette.match(s):\n # tRNS contains only one full-transparent entry,\n # other entries are full opaque\n i = s.find(b"\0")\n if i >= 0:\n self.im_info["transparency"] = i\n else:\n # otherwise, we have a byte string with one alpha value\n # for each palette entry\n self.im_info["transparency"] = s\n elif self.im_mode in ("1", "L", "I;16"):\n self.im_info["transparency"] = i16(s)\n elif self.im_mode == "RGB":\n self.im_info["transparency"] = i16(s), i16(s, 2), i16(s, 4)\n return s\n\n def chunk_gAMA(self, pos: int, length: int) -> bytes:\n # gamma setting\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n self.im_info["gamma"] = i32(s) / 100000.0\n return s\n\n def chunk_cHRM(self, pos: int, length: int) -> bytes:\n # chromaticity, 8 unsigned ints, actual value is scaled by 100,000\n # WP x,y, Red x,y, Green x,y Blue x,y\n\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n raw_vals = struct.unpack(f">{len(s) // 4}I", s)\n self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)\n return s\n\n def chunk_sRGB(self, pos: int, length: int) -> bytes:\n # srgb rendering intent, 1 byte\n # 0 perceptual\n # 1 relative colorimetric\n # 2 saturation\n # 3 absolute colorimetric\n\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if length < 1:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n msg = "Truncated sRGB chunk"\n raise ValueError(msg)\n self.im_info["srgb"] = s[0]\n return s\n\n def chunk_pHYs(self, pos: int, length: int) -> bytes:\n # pixels per unit\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if length < 9:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n msg = "Truncated pHYs chunk"\n raise ValueError(msg)\n px, py = i32(s, 0), i32(s, 4)\n unit = s[8]\n if unit == 1: # meter\n dpi = px * 0.0254, py * 0.0254\n self.im_info["dpi"] = dpi\n elif unit == 0:\n self.im_info["aspect"] = px, py\n return s\n\n def chunk_tEXt(self, pos: int, length: int) -> bytes:\n # text\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n try:\n k, v = s.split(b"\0", 1)\n except ValueError:\n # fallback for broken tEXt tags\n k = s\n v = b""\n if k:\n k_str = k.decode("latin-1", "strict")\n v_str = v.decode("latin-1", "replace")\n\n self.im_info[k_str] = v if k == b"exif" else v_str\n self.im_text[k_str] = v_str\n self.check_text_memory(len(v_str))\n\n return s\n\n def chunk_zTXt(self, pos: int, length: int) -> bytes:\n # compressed text\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n try:\n k, v = s.split(b"\0", 1)\n except ValueError:\n k = s\n v = b""\n if v:\n comp_method = v[0]\n else:\n comp_method = 0\n if comp_method != 0:\n msg = f"Unknown compression method {comp_method} in zTXt chunk"\n raise SyntaxError(msg)\n try:\n v = _safe_zlib_decompress(v[1:])\n except ValueError:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n v = b""\n else:\n raise\n except zlib.error:\n v = b""\n\n if k:\n k_str = k.decode("latin-1", "strict")\n v_str = v.decode("latin-1", "replace")\n\n self.im_info[k_str] = self.im_text[k_str] = v_str\n self.check_text_memory(len(v_str))\n\n return s\n\n def chunk_iTXt(self, pos: int, length: int) -> bytes:\n # international text\n assert self.fp is not None\n r = s = ImageFile._safe_read(self.fp, length)\n try:\n k, r = r.split(b"\0", 1)\n except ValueError:\n return s\n if len(r) < 2:\n return s\n cf, cm, r = r[0], r[1], r[2:]\n try:\n lang, tk, v = r.split(b"\0", 2)\n except ValueError:\n return s\n if cf != 0:\n if cm == 0:\n try:\n v = _safe_zlib_decompress(v)\n except ValueError:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n else:\n raise\n except zlib.error:\n return s\n else:\n return s\n if k == b"XML:com.adobe.xmp":\n self.im_info["xmp"] = v\n try:\n k_str = k.decode("latin-1", "strict")\n lang_str = lang.decode("utf-8", "strict")\n tk_str = tk.decode("utf-8", "strict")\n v_str = v.decode("utf-8", "strict")\n except UnicodeError:\n return s\n\n self.im_info[k_str] = self.im_text[k_str] = iTXt(v_str, lang_str, tk_str)\n self.check_text_memory(len(v_str))\n\n return s\n\n def chunk_eXIf(self, pos: int, length: int) -> bytes:\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n self.im_info["exif"] = b"Exif\x00\x00" + s\n return s\n\n # APNG chunks\n def chunk_acTL(self, pos: int, length: int) -> bytes:\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if length < 8:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n msg = "APNG contains truncated acTL chunk"\n raise ValueError(msg)\n if self.im_n_frames is not None:\n self.im_n_frames = None\n warnings.warn("Invalid APNG, will use default PNG image if possible")\n return s\n n_frames = i32(s)\n if n_frames == 0 or n_frames > 0x80000000:\n warnings.warn("Invalid APNG, will use default PNG image if possible")\n return s\n self.im_n_frames = n_frames\n self.im_info["loop"] = i32(s, 4)\n self.im_custom_mimetype = "image/apng"\n return s\n\n def chunk_fcTL(self, pos: int, length: int) -> bytes:\n assert self.fp is not None\n s = ImageFile._safe_read(self.fp, length)\n if length < 26:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n return s\n msg = "APNG contains truncated fcTL chunk"\n raise ValueError(msg)\n seq = i32(s)\n if (self._seq_num is None and seq != 0) or (\n self._seq_num is not None and self._seq_num != seq - 1\n ):\n msg = "APNG contains frame sequence errors"\n raise SyntaxError(msg)\n self._seq_num = seq\n width, height = i32(s, 4), i32(s, 8)\n px, py = i32(s, 12), i32(s, 16)\n im_w, im_h = self.im_size\n if px + width > im_w or py + height > im_h:\n msg = "APNG contains invalid frames"\n raise SyntaxError(msg)\n self.im_info["bbox"] = (px, py, px + width, py + height)\n delay_num, delay_den = i16(s, 20), i16(s, 22)\n if delay_den == 0:\n delay_den = 100\n self.im_info["duration"] = float(delay_num) / float(delay_den) * 1000\n self.im_info["disposal"] = s[24]\n self.im_info["blend"] = s[25]\n return s\n\n def chunk_fdAT(self, pos: int, length: int) -> bytes:\n assert self.fp is not None\n if length < 4:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n s = ImageFile._safe_read(self.fp, length)\n return s\n msg = "APNG contains truncated fDAT chunk"\n raise ValueError(msg)\n s = ImageFile._safe_read(self.fp, 4)\n seq = i32(s)\n if self._seq_num != seq - 1:\n msg = "APNG contains frame sequence errors"\n raise SyntaxError(msg)\n self._seq_num = seq\n return self.chunk_IDAT(pos + 4, length - 4)\n\n\n# --------------------------------------------------------------------\n# PNG reader\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(_MAGIC)\n\n\n##\n# Image plugin for PNG images.\n\n\nclass PngImageFile(ImageFile.ImageFile):\n format = "PNG"\n format_description = "Portable network graphics"\n\n def _open(self) -> None:\n if not _accept(self.fp.read(8)):\n msg = "not a PNG file"\n raise SyntaxError(msg)\n self._fp = self.fp\n self.__frame = 0\n\n #\n # Parse headers up to the first IDAT or fDAT chunk\n\n self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []\n self.png: PngStream | None = PngStream(self.fp)\n\n while True:\n #\n # get next chunk\n\n cid, pos, length = self.png.read()\n\n try:\n s = self.png.call(cid, pos, length)\n except EOFError:\n break\n except AttributeError:\n logger.debug("%r %s %s (unknown)", cid, pos, length)\n s = ImageFile._safe_read(self.fp, length)\n if cid[1:2].islower():\n self.private_chunks.append((cid, s))\n\n self.png.crc(cid, s)\n\n #\n # Copy relevant attributes from the PngStream. An alternative\n # would be to let the PngStream class modify these attributes\n # directly, but that introduces circular references which are\n # difficult to break if things go wrong in the decoder...\n # (believe me, I've tried ;-)\n\n self._mode = self.png.im_mode\n self._size = self.png.im_size\n self.info = self.png.im_info\n self._text: dict[str, str | iTXt] | None = None\n self.tile = self.png.im_tile\n self.custom_mimetype = self.png.im_custom_mimetype\n self.n_frames = self.png.im_n_frames or 1\n self.default_image = self.info.get("default_image", False)\n\n if self.png.im_palette:\n rawmode, data = self.png.im_palette\n self.palette = ImagePalette.raw(rawmode, data)\n\n if cid == b"fdAT":\n self.__prepare_idat = length - 4\n else:\n self.__prepare_idat = length # used by load_prepare()\n\n if self.png.im_n_frames is not None:\n self._close_exclusive_fp_after_loading = False\n self.png.save_rewind()\n self.__rewind_idat = self.__prepare_idat\n self.__rewind = self._fp.tell()\n if self.default_image:\n # IDAT chunk contains default image and not first animation frame\n self.n_frames += 1\n self._seek(0)\n self.is_animated = self.n_frames > 1\n\n @property\n def text(self) -> dict[str, str | iTXt]:\n # experimental\n if self._text is None:\n # iTxt, tEXt and zTXt chunks may appear at the end of the file\n # So load the file to ensure that they are read\n if self.is_animated:\n frame = self.__frame\n # for APNG, seek to the final frame before loading\n self.seek(self.n_frames - 1)\n self.load()\n if self.is_animated:\n self.seek(frame)\n assert self._text is not None\n return self._text\n\n def verify(self) -> None:\n """Verify PNG file"""\n\n if self.fp is None:\n msg = "verify must be called directly after open"\n raise RuntimeError(msg)\n\n # back up to beginning of IDAT block\n self.fp.seek(self.tile[0][2] - 8)\n\n assert self.png is not None\n self.png.verify()\n self.png.close()\n\n if self._exclusive_fp:\n self.fp.close()\n self.fp = None\n\n def seek(self, frame: int) -> None:\n if not self._seek_check(frame):\n return\n if frame < self.__frame:\n self._seek(0, True)\n\n last_frame = self.__frame\n for f in range(self.__frame + 1, frame + 1):\n try:\n self._seek(f)\n except EOFError as e:\n self.seek(last_frame)\n msg = "no more images in APNG file"\n raise EOFError(msg) from e\n\n def _seek(self, frame: int, rewind: bool = False) -> None:\n assert self.png is not None\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n\n self.dispose: _imaging.ImagingCore | None\n dispose_extent = None\n if frame == 0:\n if rewind:\n self._fp.seek(self.__rewind)\n self.png.rewind()\n self.__prepare_idat = self.__rewind_idat\n self._im = None\n self.info = self.png.im_info\n self.tile = self.png.im_tile\n self.fp = self._fp\n self._prev_im = None\n self.dispose = None\n self.default_image = self.info.get("default_image", False)\n self.dispose_op = self.info.get("disposal")\n self.blend_op = self.info.get("blend")\n dispose_extent = self.info.get("bbox")\n self.__frame = 0\n else:\n if frame != self.__frame + 1:\n msg = f"cannot seek to frame {frame}"\n raise ValueError(msg)\n\n # ensure previous frame was loaded\n self.load()\n\n if self.dispose:\n self.im.paste(self.dispose, self.dispose_extent)\n self._prev_im = self.im.copy()\n\n self.fp = self._fp\n\n # advance to the next frame\n if self.__prepare_idat:\n ImageFile._safe_read(self.fp, self.__prepare_idat)\n self.__prepare_idat = 0\n frame_start = False\n while True:\n self.fp.read(4) # CRC\n\n try:\n cid, pos, length = self.png.read()\n except (struct.error, SyntaxError):\n break\n\n if cid == b"IEND":\n msg = "No more images in APNG file"\n raise EOFError(msg)\n if cid == b"fcTL":\n if frame_start:\n # there must be at least one fdAT chunk between fcTL chunks\n msg = "APNG missing frame data"\n raise SyntaxError(msg)\n frame_start = True\n\n try:\n self.png.call(cid, pos, length)\n except UnicodeDecodeError:\n break\n except EOFError:\n if cid == b"fdAT":\n length -= 4\n if frame_start:\n self.__prepare_idat = length\n break\n ImageFile._safe_read(self.fp, length)\n except AttributeError:\n logger.debug("%r %s %s (unknown)", cid, pos, length)\n ImageFile._safe_read(self.fp, length)\n\n self.__frame = frame\n self.tile = self.png.im_tile\n self.dispose_op = self.info.get("disposal")\n self.blend_op = self.info.get("blend")\n dispose_extent = self.info.get("bbox")\n\n if not self.tile:\n msg = "image not found in APNG frame"\n raise EOFError(msg)\n if dispose_extent:\n self.dispose_extent: tuple[float, float, float, float] = dispose_extent\n\n # setup frame disposal (actual disposal done when needed in the next _seek())\n if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:\n self.dispose_op = Disposal.OP_BACKGROUND\n\n self.dispose = None\n if self.dispose_op == Disposal.OP_PREVIOUS:\n if self._prev_im:\n self.dispose = self._prev_im.copy()\n self.dispose = self._crop(self.dispose, self.dispose_extent)\n elif self.dispose_op == Disposal.OP_BACKGROUND:\n self.dispose = Image.core.fill(self.mode, self.size)\n self.dispose = self._crop(self.dispose, self.dispose_extent)\n\n def tell(self) -> int:\n return self.__frame\n\n def load_prepare(self) -> None:\n """internal: prepare to read PNG file"""\n\n if self.info.get("interlace"):\n self.decoderconfig = self.decoderconfig + (1,)\n\n self.__idat = self.__prepare_idat # used by load_read()\n ImageFile.ImageFile.load_prepare(self)\n\n def load_read(self, read_bytes: int) -> bytes:\n """internal: read more image data"""\n\n assert self.png is not None\n while self.__idat == 0:\n # end of chunk, skip forward to next one\n\n self.fp.read(4) # CRC\n\n cid, pos, length = self.png.read()\n\n if cid not in [b"IDAT", b"DDAT", b"fdAT"]:\n self.png.push(cid, pos, length)\n return b""\n\n if cid == b"fdAT":\n try:\n self.png.call(cid, pos, length)\n except EOFError:\n pass\n self.__idat = length - 4 # sequence_num has already been read\n else:\n self.__idat = length # empty chunks are allowed\n\n # read more data from this chunk\n if read_bytes <= 0:\n read_bytes = self.__idat\n else:\n read_bytes = min(read_bytes, self.__idat)\n\n self.__idat = self.__idat - read_bytes\n\n return self.fp.read(read_bytes)\n\n def load_end(self) -> None:\n """internal: finished reading image data"""\n assert self.png is not None\n if self.__idat != 0:\n self.fp.read(self.__idat)\n while True:\n self.fp.read(4) # CRC\n\n try:\n cid, pos, length = self.png.read()\n except (struct.error, SyntaxError):\n break\n\n if cid == b"IEND":\n break\n elif cid == b"fcTL" and self.is_animated:\n # start of the next frame, stop reading\n self.__prepare_idat = 0\n self.png.push(cid, pos, length)\n break\n\n try:\n self.png.call(cid, pos, length)\n except UnicodeDecodeError:\n break\n except EOFError:\n if cid == b"fdAT":\n length -= 4\n try:\n ImageFile._safe_read(self.fp, length)\n except OSError as e:\n if ImageFile.LOAD_TRUNCATED_IMAGES:\n break\n else:\n raise e\n except AttributeError:\n logger.debug("%r %s %s (unknown)", cid, pos, length)\n s = ImageFile._safe_read(self.fp, length)\n if cid[1:2].islower():\n self.private_chunks.append((cid, s, True))\n self._text = self.png.im_text\n if not self.is_animated:\n self.png.close()\n self.png = None\n else:\n if self._prev_im and self.blend_op == Blend.OP_OVER:\n updated = self._crop(self.im, self.dispose_extent)\n if self.im.mode == "RGB" and "transparency" in self.info:\n mask = updated.convert_transparent(\n "RGBA", self.info["transparency"]\n )\n else:\n if self.im.mode == "P" and "transparency" in self.info:\n t = self.info["transparency"]\n if isinstance(t, bytes):\n updated.putpalettealphas(t)\n elif isinstance(t, int):\n updated.putpalettealpha(t)\n mask = updated.convert("RGBA")\n self._prev_im.paste(updated, self.dispose_extent, mask)\n self.im = self._prev_im\n\n def _getexif(self) -> dict[int, Any] | None:\n if "exif" not in self.info:\n self.load()\n if "exif" not in self.info and "Raw profile type exif" not in self.info:\n return None\n return self.getexif()._get_merged_dict()\n\n def getexif(self) -> Image.Exif:\n if "exif" not in self.info:\n self.load()\n\n return super().getexif()\n\n\n# --------------------------------------------------------------------\n# PNG writer\n\n_OUTMODES = {\n # supported PIL modes, and corresponding rawmode, bit depth and color type\n "1": ("1", b"\x01", b"\x00"),\n "L;1": ("L;1", b"\x01", b"\x00"),\n "L;2": ("L;2", b"\x02", b"\x00"),\n "L;4": ("L;4", b"\x04", b"\x00"),\n "L": ("L", b"\x08", b"\x00"),\n "LA": ("LA", b"\x08", b"\x04"),\n "I": ("I;16B", b"\x10", b"\x00"),\n "I;16": ("I;16B", b"\x10", b"\x00"),\n "I;16B": ("I;16B", b"\x10", b"\x00"),\n "P;1": ("P;1", b"\x01", b"\x03"),\n "P;2": ("P;2", b"\x02", b"\x03"),\n "P;4": ("P;4", b"\x04", b"\x03"),\n "P": ("P", b"\x08", b"\x03"),\n "RGB": ("RGB", b"\x08", b"\x02"),\n "RGBA": ("RGBA", b"\x08", b"\x06"),\n}\n\n\ndef putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:\n """Write a PNG chunk (including CRC field)"""\n\n byte_data = b"".join(data)\n\n fp.write(o32(len(byte_data)) + cid)\n fp.write(byte_data)\n crc = _crc32(byte_data, _crc32(cid))\n fp.write(o32(crc))\n\n\nclass _idat:\n # wrap output from the encoder in IDAT chunks\n\n def __init__(self, fp: IO[bytes], chunk: Callable[..., None]) -> None:\n self.fp = fp\n self.chunk = chunk\n\n def write(self, data: bytes) -> None:\n self.chunk(self.fp, b"IDAT", data)\n\n\nclass _fdat:\n # wrap encoder output in fdAT chunks\n\n def __init__(self, fp: IO[bytes], chunk: Callable[..., None], seq_num: int) -> None:\n self.fp = fp\n self.chunk = chunk\n self.seq_num = seq_num\n\n def write(self, data: bytes) -> None:\n self.chunk(self.fp, b"fdAT", o32(self.seq_num), data)\n self.seq_num += 1\n\n\nclass _Frame(NamedTuple):\n im: Image.Image\n bbox: tuple[int, int, int, int] | None\n encoderinfo: dict[str, Any]\n\n\ndef _write_multiple_frames(\n im: Image.Image,\n fp: IO[bytes],\n chunk: Callable[..., None],\n mode: str,\n rawmode: str,\n default_image: Image.Image | None,\n append_images: list[Image.Image],\n) -> Image.Image | None:\n duration = im.encoderinfo.get("duration")\n loop = im.encoderinfo.get("loop", im.info.get("loop", 0))\n disposal = im.encoderinfo.get("disposal", im.info.get("disposal", Disposal.OP_NONE))\n blend = im.encoderinfo.get("blend", im.info.get("blend", Blend.OP_SOURCE))\n\n if default_image:\n chain = itertools.chain(append_images)\n else:\n chain = itertools.chain([im], append_images)\n\n im_frames: list[_Frame] = []\n frame_count = 0\n for im_seq in chain:\n for im_frame in ImageSequence.Iterator(im_seq):\n if im_frame.mode == mode:\n im_frame = im_frame.copy()\n else:\n im_frame = im_frame.convert(mode)\n encoderinfo = im.encoderinfo.copy()\n if isinstance(duration, (list, tuple)):\n encoderinfo["duration"] = duration[frame_count]\n elif duration is None and "duration" in im_frame.info:\n encoderinfo["duration"] = im_frame.info["duration"]\n if isinstance(disposal, (list, tuple)):\n encoderinfo["disposal"] = disposal[frame_count]\n if isinstance(blend, (list, tuple)):\n encoderinfo["blend"] = blend[frame_count]\n frame_count += 1\n\n if im_frames:\n previous = im_frames[-1]\n prev_disposal = previous.encoderinfo.get("disposal")\n prev_blend = previous.encoderinfo.get("blend")\n if prev_disposal == Disposal.OP_PREVIOUS and len(im_frames) < 2:\n prev_disposal = Disposal.OP_BACKGROUND\n\n if prev_disposal == Disposal.OP_BACKGROUND:\n base_im = previous.im.copy()\n dispose = Image.core.fill("RGBA", im.size, (0, 0, 0, 0))\n bbox = previous.bbox\n if bbox:\n dispose = dispose.crop(bbox)\n else:\n bbox = (0, 0) + im.size\n base_im.paste(dispose, bbox)\n elif prev_disposal == Disposal.OP_PREVIOUS:\n base_im = im_frames[-2].im\n else:\n base_im = previous.im\n delta = ImageChops.subtract_modulo(\n im_frame.convert("RGBA"), base_im.convert("RGBA")\n )\n bbox = delta.getbbox(alpha_only=False)\n if (\n not bbox\n and prev_disposal == encoderinfo.get("disposal")\n and prev_blend == encoderinfo.get("blend")\n and "duration" in encoderinfo\n ):\n previous.encoderinfo["duration"] += encoderinfo["duration"]\n continue\n else:\n bbox = None\n im_frames.append(_Frame(im_frame, bbox, encoderinfo))\n\n if len(im_frames) == 1 and not default_image:\n return im_frames[0].im\n\n # animation control\n chunk(\n fp,\n b"acTL",\n o32(len(im_frames)), # 0: num_frames\n o32(loop), # 4: num_plays\n )\n\n # default image IDAT (if it exists)\n if default_image:\n if im.mode != mode:\n im = im.convert(mode)\n ImageFile._save(\n im,\n cast(IO[bytes], _idat(fp, chunk)),\n [ImageFile._Tile("zip", (0, 0) + im.size, 0, rawmode)],\n )\n\n seq_num = 0\n for frame, frame_data in enumerate(im_frames):\n im_frame = frame_data.im\n if not frame_data.bbox:\n bbox = (0, 0) + im_frame.size\n else:\n bbox = frame_data.bbox\n im_frame = im_frame.crop(bbox)\n size = im_frame.size\n encoderinfo = frame_data.encoderinfo\n frame_duration = int(round(encoderinfo.get("duration", 0)))\n frame_disposal = encoderinfo.get("disposal", disposal)\n frame_blend = encoderinfo.get("blend", blend)\n # frame control\n chunk(\n fp,\n b"fcTL",\n o32(seq_num), # sequence_number\n o32(size[0]), # width\n o32(size[1]), # height\n o32(bbox[0]), # x_offset\n o32(bbox[1]), # y_offset\n o16(frame_duration), # delay_numerator\n o16(1000), # delay_denominator\n o8(frame_disposal), # dispose_op\n o8(frame_blend), # blend_op\n )\n seq_num += 1\n # frame data\n if frame == 0 and not default_image:\n # first frame must be in IDAT chunks for backwards compatibility\n ImageFile._save(\n im_frame,\n cast(IO[bytes], _idat(fp, chunk)),\n [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],\n )\n else:\n fdat_chunks = _fdat(fp, chunk, seq_num)\n ImageFile._save(\n im_frame,\n cast(IO[bytes], fdat_chunks),\n [ImageFile._Tile("zip", (0, 0) + im_frame.size, 0, rawmode)],\n )\n seq_num = fdat_chunks.seq_num\n return None\n\n\ndef _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n _save(im, fp, filename, save_all=True)\n\n\ndef _save(\n im: Image.Image,\n fp: IO[bytes],\n filename: str | bytes,\n chunk: Callable[..., None] = putchunk,\n save_all: bool = False,\n) -> None:\n # save an image to disk (called by the save method)\n\n if save_all:\n default_image = im.encoderinfo.get(\n "default_image", im.info.get("default_image")\n )\n modes = set()\n sizes = set()\n append_images = im.encoderinfo.get("append_images", [])\n for im_seq in itertools.chain([im], append_images):\n for im_frame in ImageSequence.Iterator(im_seq):\n modes.add(im_frame.mode)\n sizes.add(im_frame.size)\n for mode in ("RGBA", "RGB", "P"):\n if mode in modes:\n break\n else:\n mode = modes.pop()\n size = tuple(max(frame_size[i] for frame_size in sizes) for i in range(2))\n else:\n size = im.size\n mode = im.mode\n\n outmode = mode\n if mode == "P":\n #\n # attempt to minimize storage requirements for palette images\n if "bits" in im.encoderinfo:\n # number of bits specified by user\n colors = min(1 << im.encoderinfo["bits"], 256)\n else:\n # check palette contents\n if im.palette:\n colors = max(min(len(im.palette.getdata()[1]) // 3, 256), 1)\n else:\n colors = 256\n\n if colors <= 16:\n if colors <= 2:\n bits = 1\n elif colors <= 4:\n bits = 2\n else:\n bits = 4\n outmode += f";{bits}"\n\n # encoder options\n im.encoderconfig = (\n im.encoderinfo.get("optimize", False),\n im.encoderinfo.get("compress_level", -1),\n im.encoderinfo.get("compress_type", -1),\n im.encoderinfo.get("dictionary", b""),\n )\n\n # get the corresponding PNG mode\n try:\n rawmode, bit_depth, color_type = _OUTMODES[outmode]\n except KeyError as e:\n msg = f"cannot write mode {mode} as PNG"\n raise OSError(msg) from e\n if outmode == "I":\n deprecate("Saving I mode images as PNG", 13, stacklevel=4)\n\n #\n # write minimal PNG file\n\n fp.write(_MAGIC)\n\n chunk(\n fp,\n b"IHDR",\n o32(size[0]), # 0: size\n o32(size[1]),\n bit_depth,\n color_type,\n b"\0", # 10: compression\n b"\0", # 11: filter category\n b"\0", # 12: interlace flag\n )\n\n chunks = [b"cHRM", b"cICP", b"gAMA", b"sBIT", b"sRGB", b"tIME"]\n\n icc = im.encoderinfo.get("icc_profile", im.info.get("icc_profile"))\n if icc:\n # ICC profile\n # according to PNG spec, the iCCP chunk contains:\n # Profile name 1-79 bytes (character string)\n # Null separator 1 byte (null character)\n # Compression method 1 byte (0)\n # Compressed profile n bytes (zlib with deflate compression)\n name = b"ICC Profile"\n data = name + b"\0\0" + zlib.compress(icc)\n chunk(fp, b"iCCP", data)\n\n # You must either have sRGB or iCCP.\n # Disallow sRGB chunks when an iCCP-chunk has been emitted.\n chunks.remove(b"sRGB")\n\n info = im.encoderinfo.get("pnginfo")\n if info:\n chunks_multiple_allowed = [b"sPLT", b"iTXt", b"tEXt", b"zTXt"]\n for info_chunk in info.chunks:\n cid, data = info_chunk[:2]\n if cid in chunks:\n chunks.remove(cid)\n chunk(fp, cid, data)\n elif cid in chunks_multiple_allowed:\n chunk(fp, cid, data)\n elif cid[1:2].islower():\n # Private chunk\n after_idat = len(info_chunk) == 3 and info_chunk[2]\n if not after_idat:\n chunk(fp, cid, data)\n\n if im.mode == "P":\n palette_byte_number = colors * 3\n palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]\n while len(palette_bytes) < palette_byte_number:\n palette_bytes += b"\0"\n chunk(fp, b"PLTE", palette_bytes)\n\n transparency = im.encoderinfo.get("transparency", im.info.get("transparency", None))\n\n if transparency or transparency == 0:\n if im.mode == "P":\n # limit to actual palette size\n alpha_bytes = colors\n if isinstance(transparency, bytes):\n chunk(fp, b"tRNS", transparency[:alpha_bytes])\n else:\n transparency = max(0, min(255, transparency))\n alpha = b"\xff" * transparency + b"\0"\n chunk(fp, b"tRNS", alpha[:alpha_bytes])\n elif im.mode in ("1", "L", "I", "I;16"):\n transparency = max(0, min(65535, transparency))\n chunk(fp, b"tRNS", o16(transparency))\n elif im.mode == "RGB":\n red, green, blue = transparency\n chunk(fp, b"tRNS", o16(red) + o16(green) + o16(blue))\n else:\n if "transparency" in im.encoderinfo:\n # don't bother with transparency if it's an RGBA\n # and it's in the info dict. It's probably just stale.\n msg = "cannot use transparency for this mode"\n raise OSError(msg)\n else:\n if im.mode == "P" and im.im.getpalettemode() == "RGBA":\n alpha = im.im.getpalette("RGBA", "A")\n alpha_bytes = colors\n chunk(fp, b"tRNS", alpha[:alpha_bytes])\n\n dpi = im.encoderinfo.get("dpi")\n if dpi:\n chunk(\n fp,\n b"pHYs",\n o32(int(dpi[0] / 0.0254 + 0.5)),\n o32(int(dpi[1] / 0.0254 + 0.5)),\n b"\x01",\n )\n\n if info:\n chunks = [b"bKGD", b"hIST"]\n for info_chunk in info.chunks:\n cid, data = info_chunk[:2]\n if cid in chunks:\n chunks.remove(cid)\n chunk(fp, cid, data)\n\n exif = im.encoderinfo.get("exif")\n if exif:\n if isinstance(exif, Image.Exif):\n exif = exif.tobytes(8)\n if exif.startswith(b"Exif\x00\x00"):\n exif = exif[6:]\n chunk(fp, b"eXIf", exif)\n\n single_im: Image.Image | None = im\n if save_all:\n single_im = _write_multiple_frames(\n im, fp, chunk, mode, rawmode, default_image, append_images\n )\n if single_im:\n ImageFile._save(\n single_im,\n cast(IO[bytes], _idat(fp, chunk)),\n [ImageFile._Tile("zip", (0, 0) + single_im.size, 0, rawmode)],\n )\n\n if info:\n for info_chunk in info.chunks:\n cid, data = info_chunk[:2]\n if cid[1:2].islower():\n # Private chunk\n after_idat = len(info_chunk) == 3 and info_chunk[2]\n if after_idat:\n chunk(fp, cid, data)\n\n chunk(fp, b"IEND", b"")\n\n if hasattr(fp, "flush"):\n fp.flush()\n\n\n# --------------------------------------------------------------------\n# PNG chunk converter\n\n\ndef getchunks(im: Image.Image, **params: Any) -> list[tuple[bytes, bytes, bytes]]:\n """Return a list of PNG chunks representing this image."""\n from io import BytesIO\n\n chunks = []\n\n def append(fp: IO[bytes], cid: bytes, *data: bytes) -> None:\n byte_data = b"".join(data)\n crc = o32(_crc32(byte_data, _crc32(cid)))\n chunks.append((cid, byte_data, crc))\n\n fp = BytesIO()\n\n try:\n im.encoderinfo = params\n _save(im, fp, "", append)\n finally:\n del im.encoderinfo\n\n return chunks\n\n\n# --------------------------------------------------------------------\n# Registry\n\nImage.register_open(PngImageFile.format, PngImageFile, _accept)\nImage.register_save(PngImageFile.format, _save)\nImage.register_save_all(PngImageFile.format, _save_all)\n\nImage.register_extensions(PngImageFile.format, [".png", ".apng"])\n\nImage.register_mime(PngImageFile.format, "image/png")\n | .venv\Lib\site-packages\PIL\PngImagePlugin.py | PngImagePlugin.py | Python | 52,668 | 0.75 | 0.18891 | 0.107821 | node-utils | 554 | 2024-08-22T16:54:53.869300 | BSD-3-Clause | false | 4141181644a2aae6751b2948b67e0902 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# PPM support for PIL\n#\n# History:\n# 96-03-24 fl Created\n# 98-03-06 fl Write RGBA images (as RGB, that is)\n#\n# Copyright (c) Secret Labs AB 1997-98.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport math\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i16be as i16\nfrom ._binary import o8\nfrom ._binary import o32le as o32\n\n#\n# --------------------------------------------------------------------\n\nb_whitespace = b"\x20\x09\x0a\x0b\x0c\x0d"\n\nMODES = {\n # standard\n b"P1": "1",\n b"P2": "L",\n b"P3": "RGB",\n b"P4": "1",\n b"P5": "L",\n b"P6": "RGB",\n # extensions\n b"P0CMYK": "CMYK",\n b"Pf": "F",\n # PIL extensions (for test purposes only)\n b"PyP": "P",\n b"PyRGBA": "RGBA",\n b"PyCMYK": "CMYK",\n}\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"P") and prefix[1] in b"0123456fy"\n\n\n##\n# Image plugin for PBM, PGM, and PPM images.\n\n\nclass PpmImageFile(ImageFile.ImageFile):\n format = "PPM"\n format_description = "Pbmplus image"\n\n def _read_magic(self) -> bytes:\n assert self.fp is not None\n\n magic = b""\n # read until whitespace or longest available magic number\n for _ in range(6):\n c = self.fp.read(1)\n if not c or c in b_whitespace:\n break\n magic += c\n return magic\n\n def _read_token(self) -> bytes:\n assert self.fp is not None\n\n token = b""\n while len(token) <= 10: # read until next whitespace or limit of 10 characters\n c = self.fp.read(1)\n if not c:\n break\n elif c in b_whitespace: # token ended\n if not token:\n # skip whitespace at start\n continue\n break\n elif c == b"#":\n # ignores rest of the line; stops at CR, LF or EOF\n while self.fp.read(1) not in b"\r\n":\n pass\n continue\n token += c\n if not token:\n # Token was not even 1 byte\n msg = "Reached EOF while reading header"\n raise ValueError(msg)\n elif len(token) > 10:\n msg_too_long = b"Token too long in file header: %s" % token\n raise ValueError(msg_too_long)\n return token\n\n def _open(self) -> None:\n assert self.fp is not None\n\n magic_number = self._read_magic()\n try:\n mode = MODES[magic_number]\n except KeyError:\n msg = "not a PPM file"\n raise SyntaxError(msg)\n self._mode = mode\n\n if magic_number in (b"P1", b"P4"):\n self.custom_mimetype = "image/x-portable-bitmap"\n elif magic_number in (b"P2", b"P5"):\n self.custom_mimetype = "image/x-portable-graymap"\n elif magic_number in (b"P3", b"P6"):\n self.custom_mimetype = "image/x-portable-pixmap"\n\n self._size = int(self._read_token()), int(self._read_token())\n\n decoder_name = "raw"\n if magic_number in (b"P1", b"P2", b"P3"):\n decoder_name = "ppm_plain"\n\n args: str | tuple[str | int, ...]\n if mode == "1":\n args = "1;I"\n elif mode == "F":\n scale = float(self._read_token())\n if scale == 0.0 or not math.isfinite(scale):\n msg = "scale must be finite and non-zero"\n raise ValueError(msg)\n self.info["scale"] = abs(scale)\n\n rawmode = "F;32F" if scale < 0 else "F;32BF"\n args = (rawmode, 0, -1)\n else:\n maxval = int(self._read_token())\n if not 0 < maxval < 65536:\n msg = "maxval must be greater than 0 and less than 65536"\n raise ValueError(msg)\n if maxval > 255 and mode == "L":\n self._mode = "I"\n\n rawmode = mode\n if decoder_name != "ppm_plain":\n # If maxval matches a bit depth, use the raw decoder directly\n if maxval == 65535 and mode == "L":\n rawmode = "I;16B"\n elif maxval != 255:\n decoder_name = "ppm"\n\n args = rawmode if decoder_name == "raw" else (rawmode, maxval)\n self.tile = [\n ImageFile._Tile(decoder_name, (0, 0) + self.size, self.fp.tell(), args)\n ]\n\n\n#\n# --------------------------------------------------------------------\n\n\nclass PpmPlainDecoder(ImageFile.PyDecoder):\n _pulls_fd = True\n _comment_spans: bool\n\n def _read_block(self) -> bytes:\n assert self.fd is not None\n\n return self.fd.read(ImageFile.SAFEBLOCK)\n\n def _find_comment_end(self, block: bytes, start: int = 0) -> int:\n a = block.find(b"\n", start)\n b = block.find(b"\r", start)\n return min(a, b) if a * b > 0 else max(a, b) # lowest nonnegative index (or -1)\n\n def _ignore_comments(self, block: bytes) -> bytes:\n if self._comment_spans:\n # Finish current comment\n while block:\n comment_end = self._find_comment_end(block)\n if comment_end != -1:\n # Comment ends in this block\n # Delete tail of comment\n block = block[comment_end + 1 :]\n break\n else:\n # Comment spans whole block\n # So read the next block, looking for the end\n block = self._read_block()\n\n # Search for any further comments\n self._comment_spans = False\n while True:\n comment_start = block.find(b"#")\n if comment_start == -1:\n # No comment found\n break\n comment_end = self._find_comment_end(block, comment_start)\n if comment_end != -1:\n # Comment ends in this block\n # Delete comment\n block = block[:comment_start] + block[comment_end + 1 :]\n else:\n # Comment continues to next block(s)\n block = block[:comment_start]\n self._comment_spans = True\n break\n return block\n\n def _decode_bitonal(self) -> bytearray:\n """\n This is a separate method because in the plain PBM format, all data tokens are\n exactly one byte, so the inter-token whitespace is optional.\n """\n data = bytearray()\n total_bytes = self.state.xsize * self.state.ysize\n\n while len(data) != total_bytes:\n block = self._read_block() # read next block\n if not block:\n # eof\n break\n\n block = self._ignore_comments(block)\n\n tokens = b"".join(block.split())\n for token in tokens:\n if token not in (48, 49):\n msg = b"Invalid token for this mode: %s" % bytes([token])\n raise ValueError(msg)\n data = (data + tokens)[:total_bytes]\n invert = bytes.maketrans(b"01", b"\xff\x00")\n return data.translate(invert)\n\n def _decode_blocks(self, maxval: int) -> bytearray:\n data = bytearray()\n max_len = 10\n out_byte_count = 4 if self.mode == "I" else 1\n out_max = 65535 if self.mode == "I" else 255\n bands = Image.getmodebands(self.mode)\n total_bytes = self.state.xsize * self.state.ysize * bands * out_byte_count\n\n half_token = b""\n while len(data) != total_bytes:\n block = self._read_block() # read next block\n if not block:\n if half_token:\n block = bytearray(b" ") # flush half_token\n else:\n # eof\n break\n\n block = self._ignore_comments(block)\n\n if half_token:\n block = half_token + block # stitch half_token to new block\n half_token = b""\n\n tokens = block.split()\n\n if block and not block[-1:].isspace(): # block might split token\n half_token = tokens.pop() # save half token for later\n if len(half_token) > max_len: # prevent buildup of half_token\n msg = (\n b"Token too long found in data: %s" % half_token[: max_len + 1]\n )\n raise ValueError(msg)\n\n for token in tokens:\n if len(token) > max_len:\n msg = b"Token too long found in data: %s" % token[: max_len + 1]\n raise ValueError(msg)\n value = int(token)\n if value < 0:\n msg_str = f"Channel value is negative: {value}"\n raise ValueError(msg_str)\n if value > maxval:\n msg_str = f"Channel value too large for this mode: {value}"\n raise ValueError(msg_str)\n value = round(value / maxval * out_max)\n data += o32(value) if self.mode == "I" else o8(value)\n if len(data) == total_bytes: # finished!\n break\n return data\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n self._comment_spans = False\n if self.mode == "1":\n data = self._decode_bitonal()\n rawmode = "1;8"\n else:\n maxval = self.args[-1]\n data = self._decode_blocks(maxval)\n rawmode = "I;32" if self.mode == "I" else self.mode\n self.set_as_raw(bytes(data), rawmode)\n return -1, 0\n\n\nclass PpmDecoder(ImageFile.PyDecoder):\n _pulls_fd = True\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n assert self.fd is not None\n\n data = bytearray()\n maxval = self.args[-1]\n in_byte_count = 1 if maxval < 256 else 2\n out_byte_count = 4 if self.mode == "I" else 1\n out_max = 65535 if self.mode == "I" else 255\n bands = Image.getmodebands(self.mode)\n dest_length = self.state.xsize * self.state.ysize * bands * out_byte_count\n while len(data) < dest_length:\n pixels = self.fd.read(in_byte_count * bands)\n if len(pixels) < in_byte_count * bands:\n # eof\n break\n for b in range(bands):\n value = (\n pixels[b] if in_byte_count == 1 else i16(pixels, b * in_byte_count)\n )\n value = min(out_max, round(value / maxval * out_max))\n data += o32(value) if self.mode == "I" else o8(value)\n rawmode = "I;32" if self.mode == "I" else self.mode\n self.set_as_raw(bytes(data), rawmode)\n return -1, 0\n\n\n#\n# --------------------------------------------------------------------\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode == "1":\n rawmode, head = "1;I", b"P4"\n elif im.mode == "L":\n rawmode, head = "L", b"P5"\n elif im.mode in ("I", "I;16"):\n rawmode, head = "I;16B", b"P5"\n elif im.mode in ("RGB", "RGBA"):\n rawmode, head = "RGB", b"P6"\n elif im.mode == "F":\n rawmode, head = "F;32F", b"Pf"\n else:\n msg = f"cannot write mode {im.mode} as PPM"\n raise OSError(msg)\n fp.write(head + b"\n%d %d\n" % im.size)\n if head == b"P6":\n fp.write(b"255\n")\n elif head == b"P5":\n if rawmode == "L":\n fp.write(b"255\n")\n else:\n fp.write(b"65535\n")\n elif head == b"Pf":\n fp.write(b"-1.0\n")\n row_order = -1 if im.mode == "F" else 1\n ImageFile._save(\n im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, row_order))]\n )\n\n\n#\n# --------------------------------------------------------------------\n\n\nImage.register_open(PpmImageFile.format, PpmImageFile, _accept)\nImage.register_save(PpmImageFile.format, _save)\n\nImage.register_decoder("ppm", PpmDecoder)\nImage.register_decoder("ppm_plain", PpmPlainDecoder)\n\nImage.register_extensions(PpmImageFile.format, [".pbm", ".pgm", ".ppm", ".pnm", ".pfm"])\n\nImage.register_mime(PpmImageFile.format, "image/x-portable-anymap")\n | .venv\Lib\site-packages\PIL\PpmImagePlugin.py | PpmImagePlugin.py | Python | 12,745 | 0.95 | 0.221333 | 0.146032 | vue-tools | 477 | 2025-01-18T18:36:37.988279 | Apache-2.0 | false | fda166854a29e95b7203300e1fb13f8e |
#\n# The Python Imaging Library\n# $Id$\n#\n# Adobe PSD 2.5/3.0 file handling\n#\n# History:\n# 1995-09-01 fl Created\n# 1997-01-03 fl Read most PSD images\n# 1997-01-18 fl Fixed P and CMYK support\n# 2001-10-21 fl Added seek/tell support (for layers)\n#\n# Copyright (c) 1997-2001 by Secret Labs AB.\n# Copyright (c) 1995-2001 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nfrom functools import cached_property\nfrom typing import IO\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i8\nfrom ._binary import i16be as i16\nfrom ._binary import i32be as i32\nfrom ._binary import si16be as si16\nfrom ._binary import si32be as si32\nfrom ._util import DeferredError\n\nMODES = {\n # (photoshop mode, bits) -> (pil mode, required channels)\n (0, 1): ("1", 1),\n (0, 8): ("L", 1),\n (1, 8): ("L", 1),\n (2, 8): ("P", 1),\n (3, 8): ("RGB", 3),\n (4, 8): ("CMYK", 4),\n (7, 8): ("L", 1), # FIXME: multilayer\n (8, 8): ("L", 1), # duotone\n (9, 8): ("LAB", 3),\n}\n\n\n# --------------------------------------------------------------------.\n# read PSD images\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"8BPS")\n\n\n##\n# Image plugin for Photoshop images.\n\n\nclass PsdImageFile(ImageFile.ImageFile):\n format = "PSD"\n format_description = "Adobe Photoshop"\n _close_exclusive_fp_after_loading = False\n\n def _open(self) -> None:\n read = self.fp.read\n\n #\n # header\n\n s = read(26)\n if not _accept(s) or i16(s, 4) != 1:\n msg = "not a PSD file"\n raise SyntaxError(msg)\n\n psd_bits = i16(s, 22)\n psd_channels = i16(s, 12)\n psd_mode = i16(s, 24)\n\n mode, channels = MODES[(psd_mode, psd_bits)]\n\n if channels > psd_channels:\n msg = "not enough channels"\n raise OSError(msg)\n if mode == "RGB" and psd_channels == 4:\n mode = "RGBA"\n channels = 4\n\n self._mode = mode\n self._size = i32(s, 18), i32(s, 14)\n\n #\n # color mode data\n\n size = i32(read(4))\n if size:\n data = read(size)\n if mode == "P" and size == 768:\n self.palette = ImagePalette.raw("RGB;L", data)\n\n #\n # image resources\n\n self.resources = []\n\n size = i32(read(4))\n if size:\n # load resources\n end = self.fp.tell() + size\n while self.fp.tell() < end:\n read(4) # signature\n id = i16(read(2))\n name = read(i8(read(1)))\n if not (len(name) & 1):\n read(1) # padding\n data = read(i32(read(4)))\n if len(data) & 1:\n read(1) # padding\n self.resources.append((id, name, data))\n if id == 1039: # ICC profile\n self.info["icc_profile"] = data\n\n #\n # layer and mask information\n\n self._layers_position = None\n\n size = i32(read(4))\n if size:\n end = self.fp.tell() + size\n size = i32(read(4))\n if size:\n self._layers_position = self.fp.tell()\n self._layers_size = size\n self.fp.seek(end)\n self._n_frames: int | None = None\n\n #\n # image descriptor\n\n self.tile = _maketile(self.fp, mode, (0, 0) + self.size, channels)\n\n # keep the file open\n self._fp = self.fp\n self.frame = 1\n self._min_frame = 1\n\n @cached_property\n def layers(\n self,\n ) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:\n layers = []\n if self._layers_position is not None:\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n self._fp.seek(self._layers_position)\n _layer_data = io.BytesIO(ImageFile._safe_read(self._fp, self._layers_size))\n layers = _layerinfo(_layer_data, self._layers_size)\n self._n_frames = len(layers)\n return layers\n\n @property\n def n_frames(self) -> int:\n if self._n_frames is None:\n self._n_frames = len(self.layers)\n return self._n_frames\n\n @property\n def is_animated(self) -> bool:\n return len(self.layers) > 1\n\n def seek(self, layer: int) -> None:\n if not self._seek_check(layer):\n return\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n\n # seek to given layer (1..max)\n _, mode, _, tile = self.layers[layer - 1]\n self._mode = mode\n self.tile = tile\n self.frame = layer\n self.fp = self._fp\n\n def tell(self) -> int:\n # return layer number (0=image, 1..max=layers)\n return self.frame\n\n\ndef _layerinfo(\n fp: IO[bytes], ct_bytes: int\n) -> list[tuple[str, str, tuple[int, int, int, int], list[ImageFile._Tile]]]:\n # read layerinfo block\n layers = []\n\n def read(size: int) -> bytes:\n return ImageFile._safe_read(fp, size)\n\n ct = si16(read(2))\n\n # sanity check\n if ct_bytes < (abs(ct) * 20):\n msg = "Layer block too short for number of layers requested"\n raise SyntaxError(msg)\n\n for _ in range(abs(ct)):\n # bounding box\n y0 = si32(read(4))\n x0 = si32(read(4))\n y1 = si32(read(4))\n x1 = si32(read(4))\n\n # image info\n bands = []\n ct_types = i16(read(2))\n if ct_types > 4:\n fp.seek(ct_types * 6 + 12, io.SEEK_CUR)\n size = i32(read(4))\n fp.seek(size, io.SEEK_CUR)\n continue\n\n for _ in range(ct_types):\n type = i16(read(2))\n\n if type == 65535:\n b = "A"\n else:\n b = "RGBA"[type]\n\n bands.append(b)\n read(4) # size\n\n # figure out the image mode\n bands.sort()\n if bands == ["R"]:\n mode = "L"\n elif bands == ["B", "G", "R"]:\n mode = "RGB"\n elif bands == ["A", "B", "G", "R"]:\n mode = "RGBA"\n else:\n mode = "" # unknown\n\n # skip over blend flags and extra information\n read(12) # filler\n name = ""\n size = i32(read(4)) # length of the extra data field\n if size:\n data_end = fp.tell() + size\n\n length = i32(read(4))\n if length:\n fp.seek(length - 16, io.SEEK_CUR)\n\n length = i32(read(4))\n if length:\n fp.seek(length, io.SEEK_CUR)\n\n length = i8(read(1))\n if length:\n # Don't know the proper encoding,\n # Latin-1 should be a good guess\n name = read(length).decode("latin-1", "replace")\n\n fp.seek(data_end)\n layers.append((name, mode, (x0, y0, x1, y1)))\n\n # get tiles\n layerinfo = []\n for i, (name, mode, bbox) in enumerate(layers):\n tile = []\n for m in mode:\n t = _maketile(fp, m, bbox, 1)\n if t:\n tile.extend(t)\n layerinfo.append((name, mode, bbox, tile))\n\n return layerinfo\n\n\ndef _maketile(\n file: IO[bytes], mode: str, bbox: tuple[int, int, int, int], channels: int\n) -> list[ImageFile._Tile]:\n tiles = []\n read = file.read\n\n compression = i16(read(2))\n\n xsize = bbox[2] - bbox[0]\n ysize = bbox[3] - bbox[1]\n\n offset = file.tell()\n\n if compression == 0:\n #\n # raw compression\n for channel in range(channels):\n layer = mode[channel]\n if mode == "CMYK":\n layer += ";I"\n tiles.append(ImageFile._Tile("raw", bbox, offset, layer))\n offset = offset + xsize * ysize\n\n elif compression == 1:\n #\n # packbits compression\n i = 0\n bytecount = read(channels * ysize * 2)\n offset = file.tell()\n for channel in range(channels):\n layer = mode[channel]\n if mode == "CMYK":\n layer += ";I"\n tiles.append(ImageFile._Tile("packbits", bbox, offset, layer))\n for y in range(ysize):\n offset = offset + i16(bytecount, i)\n i += 2\n\n file.seek(offset)\n\n if offset & 1:\n read(1) # padding\n\n return tiles\n\n\n# --------------------------------------------------------------------\n# registry\n\n\nImage.register_open(PsdImageFile.format, PsdImageFile, _accept)\n\nImage.register_extension(PsdImageFile.format, ".psd")\n\nImage.register_mime(PsdImageFile.format, "image/vnd.adobe.photoshop")\n | .venv\Lib\site-packages\PIL\PsdImagePlugin.py | PsdImagePlugin.py | Python | 9,018 | 0.95 | 0.156156 | 0.193182 | vue-tools | 912 | 2025-06-01T07:23:13.042736 | Apache-2.0 | false | e3aa50351455c1b3588fc238e0663157 |
#\n# The Python Imaging Library\n# $Id$\n#\n# Simple PostScript graphics interface\n#\n# History:\n# 1996-04-20 fl Created\n# 1999-01-10 fl Added gsave/grestore to image method\n# 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge)\n#\n# Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved.\n# Copyright (c) 1996 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport sys\nfrom typing import IO\n\nfrom . import EpsImagePlugin\n\nTYPE_CHECKING = False\n\n\n##\n# Simple PostScript graphics interface.\n\n\nclass PSDraw:\n """\n Sets up printing to the given file. If ``fp`` is omitted,\n ``sys.stdout.buffer`` is assumed.\n """\n\n def __init__(self, fp: IO[bytes] | None = None) -> None:\n if not fp:\n fp = sys.stdout.buffer\n self.fp = fp\n\n def begin_document(self, id: str | None = None) -> None:\n """Set up printing of a document. (Write PostScript DSC header.)"""\n # FIXME: incomplete\n self.fp.write(\n b"%!PS-Adobe-3.0\n"\n b"save\n"\n b"/showpage { } def\n"\n b"%%EndComments\n"\n b"%%BeginDocument\n"\n )\n # self.fp.write(ERROR_PS) # debugging!\n self.fp.write(EDROFF_PS)\n self.fp.write(VDI_PS)\n self.fp.write(b"%%EndProlog\n")\n self.isofont: dict[bytes, int] = {}\n\n def end_document(self) -> None:\n """Ends printing. (Write PostScript DSC footer.)"""\n self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n")\n if hasattr(self.fp, "flush"):\n self.fp.flush()\n\n def setfont(self, font: str, size: int) -> None:\n """\n Selects which font to use.\n\n :param font: A PostScript font name\n :param size: Size in points.\n """\n font_bytes = bytes(font, "UTF-8")\n if font_bytes not in self.isofont:\n # reencode font\n self.fp.write(\n b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes)\n )\n self.isofont[font_bytes] = 1\n # rough\n self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes))\n\n def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None:\n """\n Draws a line between the two points. Coordinates are given in\n PostScript point coordinates (72 points per inch, (0, 0) is the lower\n left corner of the page).\n """\n self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))\n\n def rectangle(self, box: tuple[int, int, int, int]) -> None:\n """\n Draws a rectangle.\n\n :param box: A tuple of four integers, specifying left, bottom, width and\n height.\n """\n self.fp.write(b"%d %d M 0 %d %d Vr\n" % box)\n\n def text(self, xy: tuple[int, int], text: str) -> None:\n """\n Draws text at the given position. You must use\n :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.\n """\n text_bytes = bytes(text, "UTF-8")\n text_bytes = b"\\(".join(text_bytes.split(b"("))\n text_bytes = b"\\)".join(text_bytes.split(b")"))\n self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,)))\n\n if TYPE_CHECKING:\n from . import Image\n\n def image(\n self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None\n ) -> None:\n """Draw a PIL image, centered in the given box."""\n # default resolution depends on mode\n if not dpi:\n if im.mode == "1":\n dpi = 200 # fax\n else:\n dpi = 100 # grayscale\n # image size (on paper)\n x = im.size[0] * 72 / dpi\n y = im.size[1] * 72 / dpi\n # max allowed size\n xmax = float(box[2] - box[0])\n ymax = float(box[3] - box[1])\n if x > xmax:\n y = y * xmax / x\n x = xmax\n if y > ymax:\n x = x * ymax / y\n y = ymax\n dx = (xmax - x) / 2 + box[0]\n dy = (ymax - y) / 2 + box[1]\n self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy))\n if (x, y) != im.size:\n # EpsImagePlugin._save prints the image at (0,0,xsize,ysize)\n sx = x / im.size[0]\n sy = y / im.size[1]\n self.fp.write(b"%f %f scale\n" % (sx, sy))\n EpsImagePlugin._save(im, self.fp, "", 0)\n self.fp.write(b"\ngrestore\n")\n\n\n# --------------------------------------------------------------------\n# PostScript driver\n\n#\n# EDROFF.PS -- PostScript driver for Edroff 2\n#\n# History:\n# 94-01-25 fl: created (edroff 2.04)\n#\n# Copyright (c) Fredrik Lundh 1994.\n#\n\n\nEDROFF_PS = b"""\\n/S { show } bind def\n/P { moveto show } bind def\n/M { moveto } bind def\n/X { 0 rmoveto } bind def\n/Y { 0 exch rmoveto } bind def\n/E { findfont\n dup maxlength dict begin\n {\n 1 index /FID ne { def } { pop pop } ifelse\n } forall\n /Encoding exch def\n dup /FontName exch def\n currentdict end definefont pop\n} bind def\n/F { findfont exch scalefont dup setfont\n [ exch /setfont cvx ] cvx bind def\n} bind def\n"""\n\n#\n# VDI.PS -- PostScript driver for VDI meta commands\n#\n# History:\n# 94-01-25 fl: created (edroff 2.04)\n#\n# Copyright (c) Fredrik Lundh 1994.\n#\n\nVDI_PS = b"""\\n/Vm { moveto } bind def\n/Va { newpath arcn stroke } bind def\n/Vl { moveto lineto stroke } bind def\n/Vc { newpath 0 360 arc closepath } bind def\n/Vr { exch dup 0 rlineto\n exch dup 0 exch rlineto\n exch neg 0 rlineto\n 0 exch neg rlineto\n setgray fill } bind def\n/Tm matrix def\n/Ve { Tm currentmatrix pop\n translate scale newpath 0 0 .5 0 360 arc closepath\n Tm setmatrix\n} bind def\n/Vf { currentgray exch setgray fill setgray } bind def\n"""\n\n#\n# ERROR.PS -- Error handler\n#\n# History:\n# 89-11-21 fl: created (pslist 1.10)\n#\n\nERROR_PS = b"""\\n/landscape false def\n/errorBUF 200 string def\n/errorNL { currentpoint 10 sub exch pop 72 exch moveto } def\nerrordict begin /handleerror {\n initmatrix /Courier findfont 10 scalefont setfont\n newpath 72 720 moveto $error begin /newerror false def\n (PostScript Error) show errorNL errorNL\n (Error: ) show\n /errorname load errorBUF cvs show errorNL errorNL\n (Command: ) show\n /command load dup type /stringtype ne { errorBUF cvs } if show\n errorNL errorNL\n (VMstatus: ) show\n vmstatus errorBUF cvs show ( bytes available, ) show\n errorBUF cvs show ( bytes used at level ) show\n errorBUF cvs show errorNL errorNL\n (Operand stargck: ) show errorNL /ostargck load {\n dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL\n } forall errorNL\n (Execution stargck: ) show errorNL /estargck load {\n dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL\n } forall\n end showpage\n} def end\n"""\n | .venv\Lib\site-packages\PIL\PSDraw.py | PSDraw.py | Python | 7,155 | 0.95 | 0.206751 | 0.238095 | python-kit | 677 | 2024-12-09T06:10:56.770928 | MIT | false | 2157b3434254a1da37256cd79af62544 |
#\n# The Python Imaging Library.\n#\n# QOI support for PIL\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport os\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i32be as i32\nfrom ._binary import o8\nfrom ._binary import o32be as o32\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"qoif")\n\n\nclass QoiImageFile(ImageFile.ImageFile):\n format = "QOI"\n format_description = "Quite OK Image"\n\n def _open(self) -> None:\n if not _accept(self.fp.read(4)):\n msg = "not a QOI file"\n raise SyntaxError(msg)\n\n self._size = i32(self.fp.read(4)), i32(self.fp.read(4))\n\n channels = self.fp.read(1)[0]\n self._mode = "RGB" if channels == 3 else "RGBA"\n\n self.fp.seek(1, os.SEEK_CUR) # colorspace\n self.tile = [ImageFile._Tile("qoi", (0, 0) + self._size, self.fp.tell())]\n\n\nclass QoiDecoder(ImageFile.PyDecoder):\n _pulls_fd = True\n _previous_pixel: bytes | bytearray | None = None\n _previously_seen_pixels: dict[int, bytes | bytearray] = {}\n\n def _add_to_previous_pixels(self, value: bytes | bytearray) -> None:\n self._previous_pixel = value\n\n r, g, b, a = value\n hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64\n self._previously_seen_pixels[hash_value] = value\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n assert self.fd is not None\n\n self._previously_seen_pixels = {}\n self._previous_pixel = bytearray((0, 0, 0, 255))\n\n data = bytearray()\n bands = Image.getmodebands(self.mode)\n dest_length = self.state.xsize * self.state.ysize * bands\n while len(data) < dest_length:\n byte = self.fd.read(1)[0]\n value: bytes | bytearray\n if byte == 0b11111110 and self._previous_pixel: # QOI_OP_RGB\n value = bytearray(self.fd.read(3)) + self._previous_pixel[3:]\n elif byte == 0b11111111: # QOI_OP_RGBA\n value = self.fd.read(4)\n else:\n op = byte >> 6\n if op == 0: # QOI_OP_INDEX\n op_index = byte & 0b00111111\n value = self._previously_seen_pixels.get(\n op_index, bytearray((0, 0, 0, 0))\n )\n elif op == 1 and self._previous_pixel: # QOI_OP_DIFF\n value = bytearray(\n (\n (self._previous_pixel[0] + ((byte & 0b00110000) >> 4) - 2)\n % 256,\n (self._previous_pixel[1] + ((byte & 0b00001100) >> 2) - 2)\n % 256,\n (self._previous_pixel[2] + (byte & 0b00000011) - 2) % 256,\n self._previous_pixel[3],\n )\n )\n elif op == 2 and self._previous_pixel: # QOI_OP_LUMA\n second_byte = self.fd.read(1)[0]\n diff_green = (byte & 0b00111111) - 32\n diff_red = ((second_byte & 0b11110000) >> 4) - 8\n diff_blue = (second_byte & 0b00001111) - 8\n\n value = bytearray(\n tuple(\n (self._previous_pixel[i] + diff_green + diff) % 256\n for i, diff in enumerate((diff_red, 0, diff_blue))\n )\n )\n value += self._previous_pixel[3:]\n elif op == 3 and self._previous_pixel: # QOI_OP_RUN\n run_length = (byte & 0b00111111) + 1\n value = self._previous_pixel\n if bands == 3:\n value = value[:3]\n data += value * run_length\n continue\n self._add_to_previous_pixels(value)\n\n if bands == 3:\n value = value[:3]\n data += value\n self.set_as_raw(data)\n return -1, 0\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode == "RGB":\n channels = 3\n elif im.mode == "RGBA":\n channels = 4\n else:\n msg = "Unsupported QOI image mode"\n raise ValueError(msg)\n\n colorspace = 0 if im.encoderinfo.get("colorspace") == "sRGB" else 1\n\n fp.write(b"qoif")\n fp.write(o32(im.size[0]))\n fp.write(o32(im.size[1]))\n fp.write(o8(channels))\n fp.write(o8(colorspace))\n\n ImageFile._save(im, fp, [ImageFile._Tile("qoi", (0, 0) + im.size)])\n\n\nclass QoiEncoder(ImageFile.PyEncoder):\n _pushes_fd = True\n _previous_pixel: tuple[int, int, int, int] | None = None\n _previously_seen_pixels: dict[int, tuple[int, int, int, int]] = {}\n _run = 0\n\n def _write_run(self) -> bytes:\n data = o8(0b11000000 | (self._run - 1)) # QOI_OP_RUN\n self._run = 0\n return data\n\n def _delta(self, left: int, right: int) -> int:\n result = (left - right) & 255\n if result >= 128:\n result -= 256\n return result\n\n def encode(self, bufsize: int) -> tuple[int, int, bytes]:\n assert self.im is not None\n\n self._previously_seen_pixels = {0: (0, 0, 0, 0)}\n self._previous_pixel = (0, 0, 0, 255)\n\n data = bytearray()\n w, h = self.im.size\n bands = Image.getmodebands(self.mode)\n\n for y in range(h):\n for x in range(w):\n pixel = self.im.getpixel((x, y))\n if bands == 3:\n pixel = (*pixel, 255)\n\n if pixel == self._previous_pixel:\n self._run += 1\n if self._run == 62:\n data += self._write_run()\n else:\n if self._run:\n data += self._write_run()\n\n r, g, b, a = pixel\n hash_value = (r * 3 + g * 5 + b * 7 + a * 11) % 64\n if self._previously_seen_pixels.get(hash_value) == pixel:\n data += o8(hash_value) # QOI_OP_INDEX\n elif self._previous_pixel:\n self._previously_seen_pixels[hash_value] = pixel\n\n prev_r, prev_g, prev_b, prev_a = self._previous_pixel\n if prev_a == a:\n delta_r = self._delta(r, prev_r)\n delta_g = self._delta(g, prev_g)\n delta_b = self._delta(b, prev_b)\n\n if (\n -2 <= delta_r < 2\n and -2 <= delta_g < 2\n and -2 <= delta_b < 2\n ):\n data += o8(\n 0b01000000\n | (delta_r + 2) << 4\n | (delta_g + 2) << 2\n | (delta_b + 2)\n ) # QOI_OP_DIFF\n else:\n delta_gr = self._delta(delta_r, delta_g)\n delta_gb = self._delta(delta_b, delta_g)\n if (\n -8 <= delta_gr < 8\n and -32 <= delta_g < 32\n and -8 <= delta_gb < 8\n ):\n data += o8(\n 0b10000000 | (delta_g + 32)\n ) # QOI_OP_LUMA\n data += o8((delta_gr + 8) << 4 | (delta_gb + 8))\n else:\n data += o8(0b11111110) # QOI_OP_RGB\n data += bytes(pixel[:3])\n else:\n data += o8(0b11111111) # QOI_OP_RGBA\n data += bytes(pixel)\n\n self._previous_pixel = pixel\n\n if self._run:\n data += self._write_run()\n data += bytes((0, 0, 0, 0, 0, 0, 0, 1)) # padding\n\n return len(data), 0, data\n\n\nImage.register_open(QoiImageFile.format, QoiImageFile, _accept)\nImage.register_decoder("qoi", QoiDecoder)\nImage.register_extension(QoiImageFile.format, ".qoi")\n\nImage.register_save(QoiImageFile.format, _save)\nImage.register_encoder("qoi", QoiEncoder)\n | .venv\Lib\site-packages\PIL\QoiImagePlugin.py | QoiImagePlugin.py | Python | 8,806 | 0.95 | 0.149573 | 0.036458 | python-kit | 395 | 2023-12-04T20:19:17.813792 | GPL-3.0 | false | 047d76e3a4cef6a83381c9993b419f8f |
from __future__ import annotations\n\nfrom .features import pilinfo\n\npilinfo(supported_formats=False)\n | .venv\Lib\site-packages\PIL\report.py | report.py | Python | 105 | 0.85 | 0 | 0 | python-kit | 274 | 2025-06-28T11:45:25.759587 | Apache-2.0 | false | d9d64ce22df3a34aa8b4dcca38ed5752 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# SGI image file handling\n#\n# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.\n# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>\n#\n#\n# History:\n# 2017-22-07 mb Add RLE decompression\n# 2016-16-10 mb Add save method without compression\n# 1995-09-10 fl Created\n#\n# Copyright (c) 2016 by Mickael Bonfill.\n# Copyright (c) 2008 by Karsten Hiddemann.\n# Copyright (c) 1997 by Secret Labs AB.\n# Copyright (c) 1995 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport os\nimport struct\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i16be as i16\nfrom ._binary import o8\n\n\ndef _accept(prefix: bytes) -> bool:\n return len(prefix) >= 2 and i16(prefix) == 474\n\n\nMODES = {\n (1, 1, 1): "L",\n (1, 2, 1): "L",\n (2, 1, 1): "L;16B",\n (2, 2, 1): "L;16B",\n (1, 3, 3): "RGB",\n (2, 3, 3): "RGB;16B",\n (1, 3, 4): "RGBA",\n (2, 3, 4): "RGBA;16B",\n}\n\n\n##\n# Image plugin for SGI images.\nclass SgiImageFile(ImageFile.ImageFile):\n format = "SGI"\n format_description = "SGI Image File Format"\n\n def _open(self) -> None:\n # HEAD\n assert self.fp is not None\n\n headlen = 512\n s = self.fp.read(headlen)\n\n if not _accept(s):\n msg = "Not an SGI image file"\n raise ValueError(msg)\n\n # compression : verbatim or RLE\n compression = s[2]\n\n # bpc : 1 or 2 bytes (8bits or 16bits)\n bpc = s[3]\n\n # dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)\n dimension = i16(s, 4)\n\n # xsize : width\n xsize = i16(s, 6)\n\n # ysize : height\n ysize = i16(s, 8)\n\n # zsize : channels count\n zsize = i16(s, 10)\n\n # determine mode from bits/zsize\n try:\n rawmode = MODES[(bpc, dimension, zsize)]\n except KeyError:\n msg = "Unsupported SGI image mode"\n raise ValueError(msg)\n\n self._size = xsize, ysize\n self._mode = rawmode.split(";")[0]\n if self.mode == "RGB":\n self.custom_mimetype = "image/rgb"\n\n # orientation -1 : scanlines begins at the bottom-left corner\n orientation = -1\n\n # decoder info\n if compression == 0:\n pagesize = xsize * ysize * bpc\n if bpc == 2:\n self.tile = [\n ImageFile._Tile(\n "SGI16",\n (0, 0) + self.size,\n headlen,\n (self.mode, 0, orientation),\n )\n ]\n else:\n self.tile = []\n offset = headlen\n for layer in self.mode:\n self.tile.append(\n ImageFile._Tile(\n "raw", (0, 0) + self.size, offset, (layer, 0, orientation)\n )\n )\n offset += pagesize\n elif compression == 1:\n self.tile = [\n ImageFile._Tile(\n "sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc)\n )\n ]\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode not in {"RGB", "RGBA", "L"}:\n msg = "Unsupported SGI image mode"\n raise ValueError(msg)\n\n # Get the keyword arguments\n info = im.encoderinfo\n\n # Byte-per-pixel precision, 1 = 8bits per pixel\n bpc = info.get("bpc", 1)\n\n if bpc not in (1, 2):\n msg = "Unsupported number of bytes per pixel"\n raise ValueError(msg)\n\n # Flip the image, since the origin of SGI file is the bottom-left corner\n orientation = -1\n # Define the file as SGI File Format\n magic_number = 474\n # Run-Length Encoding Compression - Unsupported at this time\n rle = 0\n\n # X Dimension = width / Y Dimension = height\n x, y = im.size\n # Z Dimension: Number of channels\n z = len(im.mode)\n # Number of dimensions (x,y,z)\n if im.mode == "L":\n dimension = 1 if y == 1 else 2\n else:\n dimension = 3\n\n # Minimum Byte value\n pinmin = 0\n # Maximum Byte value (255 = 8bits per pixel)\n pinmax = 255\n # Image name (79 characters max, truncated below in write)\n img_name = os.path.splitext(os.path.basename(filename))[0]\n if isinstance(img_name, str):\n img_name = img_name.encode("ascii", "ignore")\n # Standard representation of pixel in the file\n colormap = 0\n fp.write(struct.pack(">h", magic_number))\n fp.write(o8(rle))\n fp.write(o8(bpc))\n fp.write(struct.pack(">H", dimension))\n fp.write(struct.pack(">H", x))\n fp.write(struct.pack(">H", y))\n fp.write(struct.pack(">H", z))\n fp.write(struct.pack(">l", pinmin))\n fp.write(struct.pack(">l", pinmax))\n fp.write(struct.pack("4s", b"")) # dummy\n fp.write(struct.pack("79s", img_name)) # truncates to 79 chars\n fp.write(struct.pack("s", b"")) # force null byte after img_name\n fp.write(struct.pack(">l", colormap))\n fp.write(struct.pack("404s", b"")) # dummy\n\n rawmode = "L"\n if bpc == 2:\n rawmode = "L;16B"\n\n for channel in im.split():\n fp.write(channel.tobytes("raw", rawmode, 0, orientation))\n\n if hasattr(fp, "flush"):\n fp.flush()\n\n\nclass SGI16Decoder(ImageFile.PyDecoder):\n _pulls_fd = True\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n assert self.fd is not None\n assert self.im is not None\n\n rawmode, stride, orientation = self.args\n pagesize = self.state.xsize * self.state.ysize\n zsize = len(self.mode)\n self.fd.seek(512)\n\n for band in range(zsize):\n channel = Image.new("L", (self.state.xsize, self.state.ysize))\n channel.frombytes(\n self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation\n )\n self.im.putband(channel.im, band)\n\n return -1, 0\n\n\n#\n# registry\n\n\nImage.register_decoder("SGI16", SGI16Decoder)\nImage.register_open(SgiImageFile.format, SgiImageFile, _accept)\nImage.register_save(SgiImageFile.format, _save)\nImage.register_mime(SgiImageFile.format, "image/sgi")\n\nImage.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])\n\n# End of file\n | .venv\Lib\site-packages\PIL\SgiImagePlugin.py | SgiImagePlugin.py | Python | 6,620 | 0.95 | 0.099567 | 0.262032 | react-lib | 572 | 2024-12-10T03:02:24.939668 | Apache-2.0 | false | 7e278a10e1b0dfad7a73398c146e104f |
#\n# The Python Imaging Library.\n#\n# SPIDER image file handling\n#\n# History:\n# 2004-08-02 Created BB\n# 2006-03-02 added save method\n# 2006-03-13 added support for stack images\n#\n# Copyright (c) 2004 by Health Research Inc. (HRI) RENSSELAER, NY 12144.\n# Copyright (c) 2004 by William Baxter.\n# Copyright (c) 2004 by Secret Labs AB.\n# Copyright (c) 2004 by Fredrik Lundh.\n#\n\n##\n# Image plugin for the Spider image format. This format is used\n# by the SPIDER software, in processing image data from electron\n# microscopy and tomography.\n##\n\n#\n# SpiderImagePlugin.py\n#\n# The Spider image format is used by SPIDER software, in processing\n# image data from electron microscopy and tomography.\n#\n# Spider home page:\n# https://spider.wadsworth.org/spider_doc/spider/docs/spider.html\n#\n# Details about the Spider image format:\n# https://spider.wadsworth.org/spider_doc/spider/docs/image_doc.html\n#\nfrom __future__ import annotations\n\nimport os\nimport struct\nimport sys\nfrom typing import IO, Any, cast\n\nfrom . import Image, ImageFile\nfrom ._util import DeferredError\n\nTYPE_CHECKING = False\n\n\ndef isInt(f: Any) -> int:\n try:\n i = int(f)\n if f - i == 0:\n return 1\n else:\n return 0\n except (ValueError, OverflowError):\n return 0\n\n\niforms = [1, 3, -11, -12, -21, -22]\n\n\n# There is no magic number to identify Spider files, so just check a\n# series of header locations to see if they have reasonable values.\n# Returns no. of bytes in the header, if it is a valid Spider header,\n# otherwise returns 0\n\n\ndef isSpiderHeader(t: tuple[float, ...]) -> int:\n h = (99,) + t # add 1 value so can use spider header index start=1\n # header values 1,2,5,12,13,22,23 should be integers\n for i in [1, 2, 5, 12, 13, 22, 23]:\n if not isInt(h[i]):\n return 0\n # check iform\n iform = int(h[5])\n if iform not in iforms:\n return 0\n # check other header values\n labrec = int(h[13]) # no. records in file header\n labbyt = int(h[22]) # total no. of bytes in header\n lenbyt = int(h[23]) # record length in bytes\n if labbyt != (labrec * lenbyt):\n return 0\n # looks like a valid header\n return labbyt\n\n\ndef isSpiderImage(filename: str) -> int:\n with open(filename, "rb") as fp:\n f = fp.read(92) # read 23 * 4 bytes\n t = struct.unpack(">23f", f) # try big-endian first\n hdrlen = isSpiderHeader(t)\n if hdrlen == 0:\n t = struct.unpack("<23f", f) # little-endian\n hdrlen = isSpiderHeader(t)\n return hdrlen\n\n\nclass SpiderImageFile(ImageFile.ImageFile):\n format = "SPIDER"\n format_description = "Spider 2D image"\n _close_exclusive_fp_after_loading = False\n\n def _open(self) -> None:\n # check header\n n = 27 * 4 # read 27 float values\n f = self.fp.read(n)\n\n try:\n self.bigendian = 1\n t = struct.unpack(">27f", f) # try big-endian first\n hdrlen = isSpiderHeader(t)\n if hdrlen == 0:\n self.bigendian = 0\n t = struct.unpack("<27f", f) # little-endian\n hdrlen = isSpiderHeader(t)\n if hdrlen == 0:\n msg = "not a valid Spider file"\n raise SyntaxError(msg)\n except struct.error as e:\n msg = "not a valid Spider file"\n raise SyntaxError(msg) from e\n\n h = (99,) + t # add 1 value : spider header index starts at 1\n iform = int(h[5])\n if iform != 1:\n msg = "not a Spider 2D image"\n raise SyntaxError(msg)\n\n self._size = int(h[12]), int(h[2]) # size in pixels (width, height)\n self.istack = int(h[24])\n self.imgnumber = int(h[27])\n\n if self.istack == 0 and self.imgnumber == 0:\n # stk=0, img=0: a regular 2D image\n offset = hdrlen\n self._nimages = 1\n elif self.istack > 0 and self.imgnumber == 0:\n # stk>0, img=0: Opening the stack for the first time\n self.imgbytes = int(h[12]) * int(h[2]) * 4\n self.hdrlen = hdrlen\n self._nimages = int(h[26])\n # Point to the first image in the stack\n offset = hdrlen * 2\n self.imgnumber = 1\n elif self.istack == 0 and self.imgnumber > 0:\n # stk=0, img>0: an image within the stack\n offset = hdrlen + self.stkoffset\n self.istack = 2 # So Image knows it's still a stack\n else:\n msg = "inconsistent stack header values"\n raise SyntaxError(msg)\n\n if self.bigendian:\n self.rawmode = "F;32BF"\n else:\n self.rawmode = "F;32F"\n self._mode = "F"\n\n self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, offset, self.rawmode)]\n self._fp = self.fp # FIXME: hack\n\n @property\n def n_frames(self) -> int:\n return self._nimages\n\n @property\n def is_animated(self) -> bool:\n return self._nimages > 1\n\n # 1st image index is zero (although SPIDER imgnumber starts at 1)\n def tell(self) -> int:\n if self.imgnumber < 1:\n return 0\n else:\n return self.imgnumber - 1\n\n def seek(self, frame: int) -> None:\n if self.istack == 0:\n msg = "attempt to seek in a non-stack file"\n raise EOFError(msg)\n if not self._seek_check(frame):\n return\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n self.stkoffset = self.hdrlen + frame * (self.hdrlen + self.imgbytes)\n self.fp = self._fp\n self.fp.seek(self.stkoffset)\n self._open()\n\n # returns a byte image after rescaling to 0..255\n def convert2byte(self, depth: int = 255) -> Image.Image:\n extrema = self.getextrema()\n assert isinstance(extrema[0], float)\n minimum, maximum = cast(tuple[float, float], extrema)\n m: float = 1\n if maximum != minimum:\n m = depth / (maximum - minimum)\n b = -m * minimum\n return self.point(lambda i: i * m + b).convert("L")\n\n if TYPE_CHECKING:\n from . import ImageTk\n\n # returns a ImageTk.PhotoImage object, after rescaling to 0..255\n def tkPhotoImage(self) -> ImageTk.PhotoImage:\n from . import ImageTk\n\n return ImageTk.PhotoImage(self.convert2byte(), palette=256)\n\n\n# --------------------------------------------------------------------\n# Image series\n\n\n# given a list of filenames, return a list of images\ndef loadImageSeries(filelist: list[str] | None = None) -> list[Image.Image] | None:\n """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage"""\n if filelist is None or len(filelist) < 1:\n return None\n\n byte_imgs = []\n for img in filelist:\n if not os.path.exists(img):\n print(f"unable to find {img}")\n continue\n try:\n with Image.open(img) as im:\n assert isinstance(im, SpiderImageFile)\n byte_im = im.convert2byte()\n except Exception:\n if not isSpiderImage(img):\n print(f"{img} is not a Spider image file")\n continue\n byte_im.info["filename"] = img\n byte_imgs.append(byte_im)\n return byte_imgs\n\n\n# --------------------------------------------------------------------\n# For saving images in Spider format\n\n\ndef makeSpiderHeader(im: Image.Image) -> list[bytes]:\n nsam, nrow = im.size\n lenbyt = nsam * 4 # There are labrec records in the header\n labrec = int(1024 / lenbyt)\n if 1024 % lenbyt != 0:\n labrec += 1\n labbyt = labrec * lenbyt\n nvalues = int(labbyt / 4)\n if nvalues < 23:\n return []\n\n hdr = [0.0] * nvalues\n\n # NB these are Fortran indices\n hdr[1] = 1.0 # nslice (=1 for an image)\n hdr[2] = float(nrow) # number of rows per slice\n hdr[3] = float(nrow) # number of records in the image\n hdr[5] = 1.0 # iform for 2D image\n hdr[12] = float(nsam) # number of pixels per line\n hdr[13] = float(labrec) # number of records in file header\n hdr[22] = float(labbyt) # total number of bytes in header\n hdr[23] = float(lenbyt) # record length in bytes\n\n # adjust for Fortran indexing\n hdr = hdr[1:]\n hdr.append(0.0)\n # pack binary data into a string\n return [struct.pack("f", v) for v in hdr]\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode != "F":\n im = im.convert("F")\n\n hdr = makeSpiderHeader(im)\n if len(hdr) < 256:\n msg = "Error creating Spider header"\n raise OSError(msg)\n\n # write the SPIDER header\n fp.writelines(hdr)\n\n rawmode = "F;32NF" # 32-bit native floating point\n ImageFile._save(im, fp, [ImageFile._Tile("raw", (0, 0) + im.size, 0, rawmode)])\n\n\ndef _save_spider(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n # get the filename extension and register it with Image\n filename_ext = os.path.splitext(filename)[1]\n ext = filename_ext.decode() if isinstance(filename_ext, bytes) else filename_ext\n Image.register_extension(SpiderImageFile.format, ext)\n _save(im, fp, filename)\n\n\n# --------------------------------------------------------------------\n\n\nImage.register_open(SpiderImageFile.format, SpiderImageFile)\nImage.register_save(SpiderImageFile.format, _save_spider)\n\nif __name__ == "__main__":\n if len(sys.argv) < 2:\n print("Syntax: python3 SpiderImagePlugin.py [infile] [outfile]")\n sys.exit()\n\n filename = sys.argv[1]\n if not isSpiderImage(filename):\n print("input image must be in Spider format")\n sys.exit()\n\n with Image.open(filename) as im:\n print(f"image: {im}")\n print(f"format: {im.format}")\n print(f"size: {im.size}")\n print(f"mode: {im.mode}")\n print("max, min: ", end=" ")\n print(im.getextrema())\n\n if len(sys.argv) > 2:\n outfile = sys.argv[2]\n\n # perform some image operation\n im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n print(\n f"saving a flipped version of {os.path.basename(filename)} "\n f"as {outfile} "\n )\n im.save(outfile, SpiderImageFile.format)\n | .venv\Lib\site-packages\PIL\SpiderImagePlugin.py | SpiderImagePlugin.py | Python | 10,580 | 0.95 | 0.18429 | 0.221402 | vue-tools | 929 | 2024-02-24T04:53:38.077324 | GPL-3.0 | false | eb975ace18919b3521f3bfb8e7fb844e |
#\n# The Python Imaging Library.\n# $Id$\n#\n# Sun image file handling\n#\n# History:\n# 1995-09-10 fl Created\n# 1996-05-28 fl Fixed 32-bit alignment\n# 1998-12-29 fl Import ImagePalette module\n# 2001-12-18 fl Fixed palette loading (from Jean-Claude Rimbault)\n#\n# Copyright (c) 1997-2001 by Secret Labs AB\n# Copyright (c) 1995-1996 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i32be as i32\n\n\ndef _accept(prefix: bytes) -> bool:\n return len(prefix) >= 4 and i32(prefix) == 0x59A66A95\n\n\n##\n# Image plugin for Sun raster files.\n\n\nclass SunImageFile(ImageFile.ImageFile):\n format = "SUN"\n format_description = "Sun Raster File"\n\n def _open(self) -> None:\n # The Sun Raster file header is 32 bytes in length\n # and has the following format:\n\n # typedef struct _SunRaster\n # {\n # DWORD MagicNumber; /* Magic (identification) number */\n # DWORD Width; /* Width of image in pixels */\n # DWORD Height; /* Height of image in pixels */\n # DWORD Depth; /* Number of bits per pixel */\n # DWORD Length; /* Size of image data in bytes */\n # DWORD Type; /* Type of raster file */\n # DWORD ColorMapType; /* Type of color map */\n # DWORD ColorMapLength; /* Size of the color map in bytes */\n # } SUNRASTER;\n\n assert self.fp is not None\n\n # HEAD\n s = self.fp.read(32)\n if not _accept(s):\n msg = "not an SUN raster file"\n raise SyntaxError(msg)\n\n offset = 32\n\n self._size = i32(s, 4), i32(s, 8)\n\n depth = i32(s, 12)\n # data_length = i32(s, 16) # unreliable, ignore.\n file_type = i32(s, 20)\n palette_type = i32(s, 24) # 0: None, 1: RGB, 2: Raw/arbitrary\n palette_length = i32(s, 28)\n\n if depth == 1:\n self._mode, rawmode = "1", "1;I"\n elif depth == 4:\n self._mode, rawmode = "L", "L;4"\n elif depth == 8:\n self._mode = rawmode = "L"\n elif depth == 24:\n if file_type == 3:\n self._mode, rawmode = "RGB", "RGB"\n else:\n self._mode, rawmode = "RGB", "BGR"\n elif depth == 32:\n if file_type == 3:\n self._mode, rawmode = "RGB", "RGBX"\n else:\n self._mode, rawmode = "RGB", "BGRX"\n else:\n msg = "Unsupported Mode/Bit Depth"\n raise SyntaxError(msg)\n\n if palette_length:\n if palette_length > 1024:\n msg = "Unsupported Color Palette Length"\n raise SyntaxError(msg)\n\n if palette_type != 1:\n msg = "Unsupported Palette Type"\n raise SyntaxError(msg)\n\n offset = offset + palette_length\n self.palette = ImagePalette.raw("RGB;L", self.fp.read(palette_length))\n if self.mode == "L":\n self._mode = "P"\n rawmode = rawmode.replace("L", "P")\n\n # 16 bit boundaries on stride\n stride = ((self.size[0] * depth + 15) // 16) * 2\n\n # file type: Type is the version (or flavor) of the bitmap\n # file. The following values are typically found in the Type\n # field:\n # 0000h Old\n # 0001h Standard\n # 0002h Byte-encoded\n # 0003h RGB format\n # 0004h TIFF format\n # 0005h IFF format\n # FFFFh Experimental\n\n # Old and standard are the same, except for the length tag.\n # byte-encoded is run-length-encoded\n # RGB looks similar to standard, but RGB byte order\n # TIFF and IFF mean that they were converted from T/IFF\n # Experimental means that it's something else.\n # (https://www.fileformat.info/format/sunraster/egff.htm)\n\n if file_type in (0, 1, 3, 4, 5):\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, offset, (rawmode, stride))\n ]\n elif file_type == 2:\n self.tile = [\n ImageFile._Tile("sun_rle", (0, 0) + self.size, offset, rawmode)\n ]\n else:\n msg = "Unsupported Sun Raster file type"\n raise SyntaxError(msg)\n\n\n#\n# registry\n\n\nImage.register_open(SunImageFile.format, SunImageFile, _accept)\n\nImage.register_extension(SunImageFile.format, ".ras")\n | .venv\Lib\site-packages\PIL\SunImagePlugin.py | SunImagePlugin.py | Python | 4,734 | 0.95 | 0.103448 | 0.449153 | awesome-app | 315 | 2024-03-11T02:54:54.992783 | MIT | false | 8a16f31210f1e7e294ab11cb9aa2d09e |
#\n# The Python Imaging Library.\n# $Id$\n#\n# read files from within a tar file\n#\n# History:\n# 95-06-18 fl Created\n# 96-05-28 fl Open files in binary mode\n#\n# Copyright (c) Secret Labs AB 1997.\n# Copyright (c) Fredrik Lundh 1995-96.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\n\nfrom . import ContainerIO\n\n\nclass TarIO(ContainerIO.ContainerIO[bytes]):\n """A file object that provides read access to a given member of a TAR file."""\n\n def __init__(self, tarfile: str, file: str) -> None:\n """\n Create file object.\n\n :param tarfile: Name of TAR file.\n :param file: Name of member file.\n """\n self.fh = open(tarfile, "rb")\n\n while True:\n s = self.fh.read(512)\n if len(s) != 512:\n self.fh.close()\n\n msg = "unexpected end of tar file"\n raise OSError(msg)\n\n name = s[:100].decode("utf-8")\n i = name.find("\0")\n if i == 0:\n self.fh.close()\n\n msg = "cannot find subfile"\n raise OSError(msg)\n if i > 0:\n name = name[:i]\n\n size = int(s[124:135], 8)\n\n if file == name:\n break\n\n self.fh.seek((size + 511) & (~511), io.SEEK_CUR)\n\n # Open region\n super().__init__(self.fh, self.fh.tell(), size)\n | .venv\Lib\site-packages\PIL\TarIO.py | TarIO.py | Python | 1,503 | 0.95 | 0.131148 | 0.340426 | python-kit | 574 | 2025-05-01T09:26:31.747962 | MIT | false | 739efdd20e7983795012e0ceeb32d4dd |
#\n# The Python Imaging Library.\n# $Id$\n#\n# TGA file handling\n#\n# History:\n# 95-09-01 fl created (reads 24-bit files only)\n# 97-01-04 fl support more TGA versions, including compressed images\n# 98-07-04 fl fixed orientation and alpha layer bugs\n# 98-09-11 fl fixed orientation for runlength decoder\n#\n# Copyright (c) Secret Labs AB 1997-98.\n# Copyright (c) Fredrik Lundh 1995-97.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport warnings\nfrom typing import IO\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import i16le as i16\nfrom ._binary import o8\nfrom ._binary import o16le as o16\n\n#\n# --------------------------------------------------------------------\n# Read RGA file\n\n\nMODES = {\n # map imagetype/depth to rawmode\n (1, 8): "P",\n (3, 1): "1",\n (3, 8): "L",\n (3, 16): "LA",\n (2, 16): "BGRA;15Z",\n (2, 24): "BGR",\n (2, 32): "BGRA",\n}\n\n\n##\n# Image plugin for Targa files.\n\n\nclass TgaImageFile(ImageFile.ImageFile):\n format = "TGA"\n format_description = "Targa"\n\n def _open(self) -> None:\n # process header\n assert self.fp is not None\n\n s = self.fp.read(18)\n\n id_len = s[0]\n\n colormaptype = s[1]\n imagetype = s[2]\n\n depth = s[16]\n\n flags = s[17]\n\n self._size = i16(s, 12), i16(s, 14)\n\n # validate header fields\n if (\n colormaptype not in (0, 1)\n or self.size[0] <= 0\n or self.size[1] <= 0\n or depth not in (1, 8, 16, 24, 32)\n ):\n msg = "not a TGA file"\n raise SyntaxError(msg)\n\n # image mode\n if imagetype in (3, 11):\n self._mode = "L"\n if depth == 1:\n self._mode = "1" # ???\n elif depth == 16:\n self._mode = "LA"\n elif imagetype in (1, 9):\n self._mode = "P" if colormaptype else "L"\n elif imagetype in (2, 10):\n self._mode = "RGB" if depth == 24 else "RGBA"\n else:\n msg = "unknown TGA mode"\n raise SyntaxError(msg)\n\n # orientation\n orientation = flags & 0x30\n self._flip_horizontally = orientation in [0x10, 0x30]\n if orientation in [0x20, 0x30]:\n orientation = 1\n elif orientation in [0, 0x10]:\n orientation = -1\n else:\n msg = "unknown TGA orientation"\n raise SyntaxError(msg)\n\n self.info["orientation"] = orientation\n\n if imagetype & 8:\n self.info["compression"] = "tga_rle"\n\n if id_len:\n self.info["id_section"] = self.fp.read(id_len)\n\n if colormaptype:\n # read palette\n start, size, mapdepth = i16(s, 3), i16(s, 5), s[7]\n if mapdepth == 16:\n self.palette = ImagePalette.raw(\n "BGRA;15Z", bytes(2 * start) + self.fp.read(2 * size)\n )\n self.palette.mode = "RGBA"\n elif mapdepth == 24:\n self.palette = ImagePalette.raw(\n "BGR", bytes(3 * start) + self.fp.read(3 * size)\n )\n elif mapdepth == 32:\n self.palette = ImagePalette.raw(\n "BGRA", bytes(4 * start) + self.fp.read(4 * size)\n )\n else:\n msg = "unknown TGA map depth"\n raise SyntaxError(msg)\n\n # setup tile descriptor\n try:\n rawmode = MODES[(imagetype & 7, depth)]\n if imagetype & 8:\n # compressed\n self.tile = [\n ImageFile._Tile(\n "tga_rle",\n (0, 0) + self.size,\n self.fp.tell(),\n (rawmode, orientation, depth),\n )\n ]\n else:\n self.tile = [\n ImageFile._Tile(\n "raw",\n (0, 0) + self.size,\n self.fp.tell(),\n (rawmode, 0, orientation),\n )\n ]\n except KeyError:\n pass # cannot decode\n\n def load_end(self) -> None:\n if self._flip_horizontally:\n self.im = self.im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)\n\n\n#\n# --------------------------------------------------------------------\n# Write TGA file\n\n\nSAVE = {\n "1": ("1", 1, 0, 3),\n "L": ("L", 8, 0, 3),\n "LA": ("LA", 16, 0, 3),\n "P": ("P", 8, 1, 1),\n "RGB": ("BGR", 24, 0, 2),\n "RGBA": ("BGRA", 32, 0, 2),\n}\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n try:\n rawmode, bits, colormaptype, imagetype = SAVE[im.mode]\n except KeyError as e:\n msg = f"cannot write mode {im.mode} as TGA"\n raise OSError(msg) from e\n\n if "rle" in im.encoderinfo:\n rle = im.encoderinfo["rle"]\n else:\n compression = im.encoderinfo.get("compression", im.info.get("compression"))\n rle = compression == "tga_rle"\n if rle:\n imagetype += 8\n\n id_section = im.encoderinfo.get("id_section", im.info.get("id_section", ""))\n id_len = len(id_section)\n if id_len > 255:\n id_len = 255\n id_section = id_section[:255]\n warnings.warn("id_section has been trimmed to 255 characters")\n\n if colormaptype:\n palette = im.im.getpalette("RGB", "BGR")\n colormaplength, colormapentry = len(palette) // 3, 24\n else:\n colormaplength, colormapentry = 0, 0\n\n if im.mode in ("LA", "RGBA"):\n flags = 8\n else:\n flags = 0\n\n orientation = im.encoderinfo.get("orientation", im.info.get("orientation", -1))\n if orientation > 0:\n flags = flags | 0x20\n\n fp.write(\n o8(id_len)\n + o8(colormaptype)\n + o8(imagetype)\n + o16(0) # colormapfirst\n + o16(colormaplength)\n + o8(colormapentry)\n + o16(0)\n + o16(0)\n + o16(im.size[0])\n + o16(im.size[1])\n + o8(bits)\n + o8(flags)\n )\n\n if id_section:\n fp.write(id_section)\n\n if colormaptype:\n fp.write(palette)\n\n if rle:\n ImageFile._save(\n im,\n fp,\n [ImageFile._Tile("tga_rle", (0, 0) + im.size, 0, (rawmode, orientation))],\n )\n else:\n ImageFile._save(\n im,\n fp,\n [ImageFile._Tile("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))],\n )\n\n # write targa version 2 footer\n fp.write(b"\000" * 8 + b"TRUEVISION-XFILE." + b"\000")\n\n\n#\n# --------------------------------------------------------------------\n# Registry\n\n\nImage.register_open(TgaImageFile.format, TgaImageFile)\nImage.register_save(TgaImageFile.format, _save)\n\nImage.register_extensions(TgaImageFile.format, [".tga", ".icb", ".vda", ".vst"])\n\nImage.register_mime(TgaImageFile.format, "image/x-tga")\n | .venv\Lib\site-packages\PIL\TgaImagePlugin.py | TgaImagePlugin.py | Python | 7,244 | 0.95 | 0.113636 | 0.170507 | python-kit | 52 | 2025-06-15T05:22:10.739364 | BSD-3-Clause | false | bf799747f55dc9e968a1fc335e5d1b12 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# TIFF file handling\n#\n# TIFF is a flexible, if somewhat aged, image file format originally\n# defined by Aldus. Although TIFF supports a wide variety of pixel\n# layouts and compression methods, the name doesn't really stand for\n# "thousands of incompatible file formats," it just feels that way.\n#\n# To read TIFF data from a stream, the stream must be seekable. For\n# progressive decoding, make sure to use TIFF files where the tag\n# directory is placed first in the file.\n#\n# History:\n# 1995-09-01 fl Created\n# 1996-05-04 fl Handle JPEGTABLES tag\n# 1996-05-18 fl Fixed COLORMAP support\n# 1997-01-05 fl Fixed PREDICTOR support\n# 1997-08-27 fl Added support for rational tags (from Perry Stoll)\n# 1998-01-10 fl Fixed seek/tell (from Jan Blom)\n# 1998-07-15 fl Use private names for internal variables\n# 1999-06-13 fl Rewritten for PIL 1.0 (1.0)\n# 2000-10-11 fl Additional fixes for Python 2.0 (1.1)\n# 2001-04-17 fl Fixed rewind support (seek to frame 0) (1.2)\n# 2001-05-12 fl Added write support for more tags (from Greg Couch) (1.3)\n# 2001-12-18 fl Added workaround for broken Matrox library\n# 2002-01-18 fl Don't mess up if photometric tag is missing (D. Alan Stewart)\n# 2003-05-19 fl Check FILLORDER tag\n# 2003-09-26 fl Added RGBa support\n# 2004-02-24 fl Added DPI support; fixed rational write support\n# 2005-02-07 fl Added workaround for broken Corel Draw 10 files\n# 2006-01-09 fl Added support for float/double tags (from Russell Nelson)\n#\n# Copyright (c) 1997-2006 by Secret Labs AB. All rights reserved.\n# Copyright (c) 1995-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport io\nimport itertools\nimport logging\nimport math\nimport os\nimport struct\nimport warnings\nfrom collections.abc import Iterator, MutableMapping\nfrom fractions import Fraction\nfrom numbers import Number, Rational\nfrom typing import IO, Any, Callable, NoReturn, cast\n\nfrom . import ExifTags, Image, ImageFile, ImageOps, ImagePalette, TiffTags\nfrom ._binary import i16be as i16\nfrom ._binary import i32be as i32\nfrom ._binary import o8\nfrom ._deprecate import deprecate\nfrom ._typing import StrOrBytesPath\nfrom ._util import DeferredError, is_path\nfrom .TiffTags import TYPES\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from ._typing import Buffer, IntegralLike\n\nlogger = logging.getLogger(__name__)\n\n# Set these to true to force use of libtiff for reading or writing.\nREAD_LIBTIFF = False\nWRITE_LIBTIFF = False\nSTRIP_SIZE = 65536\n\nII = b"II" # little-endian (Intel style)\nMM = b"MM" # big-endian (Motorola style)\n\n#\n# --------------------------------------------------------------------\n# Read TIFF files\n\n# a few tag names, just to make the code below a bit more readable\nOSUBFILETYPE = 255\nIMAGEWIDTH = 256\nIMAGELENGTH = 257\nBITSPERSAMPLE = 258\nCOMPRESSION = 259\nPHOTOMETRIC_INTERPRETATION = 262\nFILLORDER = 266\nIMAGEDESCRIPTION = 270\nSTRIPOFFSETS = 273\nSAMPLESPERPIXEL = 277\nROWSPERSTRIP = 278\nSTRIPBYTECOUNTS = 279\nX_RESOLUTION = 282\nY_RESOLUTION = 283\nPLANAR_CONFIGURATION = 284\nRESOLUTION_UNIT = 296\nTRANSFERFUNCTION = 301\nSOFTWARE = 305\nDATE_TIME = 306\nARTIST = 315\nPREDICTOR = 317\nCOLORMAP = 320\nTILEWIDTH = 322\nTILELENGTH = 323\nTILEOFFSETS = 324\nTILEBYTECOUNTS = 325\nSUBIFD = 330\nEXTRASAMPLES = 338\nSAMPLEFORMAT = 339\nJPEGTABLES = 347\nYCBCRSUBSAMPLING = 530\nREFERENCEBLACKWHITE = 532\nCOPYRIGHT = 33432\nIPTC_NAA_CHUNK = 33723 # newsphoto properties\nPHOTOSHOP_CHUNK = 34377 # photoshop properties\nICCPROFILE = 34675\nEXIFIFD = 34665\nXMP = 700\nJPEGQUALITY = 65537 # pseudo-tag by libtiff\n\n# https://github.com/imagej/ImageJA/blob/master/src/main/java/ij/io/TiffDecoder.java\nIMAGEJ_META_DATA_BYTE_COUNTS = 50838\nIMAGEJ_META_DATA = 50839\n\nCOMPRESSION_INFO = {\n # Compression => pil compression name\n 1: "raw",\n 2: "tiff_ccitt",\n 3: "group3",\n 4: "group4",\n 5: "tiff_lzw",\n 6: "tiff_jpeg", # obsolete\n 7: "jpeg",\n 8: "tiff_adobe_deflate",\n 32771: "tiff_raw_16", # 16-bit padding\n 32773: "packbits",\n 32809: "tiff_thunderscan",\n 32946: "tiff_deflate",\n 34676: "tiff_sgilog",\n 34677: "tiff_sgilog24",\n 34925: "lzma",\n 50000: "zstd",\n 50001: "webp",\n}\n\nCOMPRESSION_INFO_REV = {v: k for k, v in COMPRESSION_INFO.items()}\n\nOPEN_INFO = {\n # (ByteOrder, PhotoInterpretation, SampleFormat, FillOrder, BitsPerSample,\n # ExtraSamples) => mode, rawmode\n (II, 0, (1,), 1, (1,), ()): ("1", "1;I"),\n (MM, 0, (1,), 1, (1,), ()): ("1", "1;I"),\n (II, 0, (1,), 2, (1,), ()): ("1", "1;IR"),\n (MM, 0, (1,), 2, (1,), ()): ("1", "1;IR"),\n (II, 1, (1,), 1, (1,), ()): ("1", "1"),\n (MM, 1, (1,), 1, (1,), ()): ("1", "1"),\n (II, 1, (1,), 2, (1,), ()): ("1", "1;R"),\n (MM, 1, (1,), 2, (1,), ()): ("1", "1;R"),\n (II, 0, (1,), 1, (2,), ()): ("L", "L;2I"),\n (MM, 0, (1,), 1, (2,), ()): ("L", "L;2I"),\n (II, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),\n (MM, 0, (1,), 2, (2,), ()): ("L", "L;2IR"),\n (II, 1, (1,), 1, (2,), ()): ("L", "L;2"),\n (MM, 1, (1,), 1, (2,), ()): ("L", "L;2"),\n (II, 1, (1,), 2, (2,), ()): ("L", "L;2R"),\n (MM, 1, (1,), 2, (2,), ()): ("L", "L;2R"),\n (II, 0, (1,), 1, (4,), ()): ("L", "L;4I"),\n (MM, 0, (1,), 1, (4,), ()): ("L", "L;4I"),\n (II, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),\n (MM, 0, (1,), 2, (4,), ()): ("L", "L;4IR"),\n (II, 1, (1,), 1, (4,), ()): ("L", "L;4"),\n (MM, 1, (1,), 1, (4,), ()): ("L", "L;4"),\n (II, 1, (1,), 2, (4,), ()): ("L", "L;4R"),\n (MM, 1, (1,), 2, (4,), ()): ("L", "L;4R"),\n (II, 0, (1,), 1, (8,), ()): ("L", "L;I"),\n (MM, 0, (1,), 1, (8,), ()): ("L", "L;I"),\n (II, 0, (1,), 2, (8,), ()): ("L", "L;IR"),\n (MM, 0, (1,), 2, (8,), ()): ("L", "L;IR"),\n (II, 1, (1,), 1, (8,), ()): ("L", "L"),\n (MM, 1, (1,), 1, (8,), ()): ("L", "L"),\n (II, 1, (2,), 1, (8,), ()): ("L", "L"),\n (MM, 1, (2,), 1, (8,), ()): ("L", "L"),\n (II, 1, (1,), 2, (8,), ()): ("L", "L;R"),\n (MM, 1, (1,), 2, (8,), ()): ("L", "L;R"),\n (II, 1, (1,), 1, (12,), ()): ("I;16", "I;12"),\n (II, 0, (1,), 1, (16,), ()): ("I;16", "I;16"),\n (II, 1, (1,), 1, (16,), ()): ("I;16", "I;16"),\n (MM, 1, (1,), 1, (16,), ()): ("I;16B", "I;16B"),\n (II, 1, (1,), 2, (16,), ()): ("I;16", "I;16R"),\n (II, 1, (2,), 1, (16,), ()): ("I", "I;16S"),\n (MM, 1, (2,), 1, (16,), ()): ("I", "I;16BS"),\n (II, 0, (3,), 1, (32,), ()): ("F", "F;32F"),\n (MM, 0, (3,), 1, (32,), ()): ("F", "F;32BF"),\n (II, 1, (1,), 1, (32,), ()): ("I", "I;32N"),\n (II, 1, (2,), 1, (32,), ()): ("I", "I;32S"),\n (MM, 1, (2,), 1, (32,), ()): ("I", "I;32BS"),\n (II, 1, (3,), 1, (32,), ()): ("F", "F;32F"),\n (MM, 1, (3,), 1, (32,), ()): ("F", "F;32BF"),\n (II, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),\n (MM, 1, (1,), 1, (8, 8), (2,)): ("LA", "LA"),\n (II, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),\n (MM, 2, (1,), 1, (8, 8, 8), ()): ("RGB", "RGB"),\n (II, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),\n (MM, 2, (1,), 2, (8, 8, 8), ()): ("RGB", "RGB;R"),\n (II, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples\n (MM, 2, (1,), 1, (8, 8, 8, 8), ()): ("RGBA", "RGBA"), # missing ExtraSamples\n (II, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8), (0,)): ("RGB", "RGBX"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (0, 0)): ("RGB", "RGBXX"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0, 0)): ("RGB", "RGBXXX"),\n (II, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),\n (MM, 2, (1,), 1, (8, 8, 8, 8), (1,)): ("RGBA", "RGBa"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (1, 0)): ("RGBA", "RGBaX"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (1, 0, 0)): ("RGBA", "RGBaXX"),\n (II, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),\n (MM, 2, (1,), 1, (8, 8, 8, 8), (2,)): ("RGBA", "RGBA"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8), (2, 0)): ("RGBA", "RGBAX"),\n (II, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),\n (MM, 2, (1,), 1, (8, 8, 8, 8, 8, 8), (2, 0, 0)): ("RGBA", "RGBAXX"),\n (II, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10\n (MM, 2, (1,), 1, (8, 8, 8, 8), (999,)): ("RGBA", "RGBA"), # Corel Draw 10\n (II, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16L"),\n (MM, 2, (1,), 1, (16, 16, 16), ()): ("RGB", "RGB;16B"),\n (II, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16L"),\n (MM, 2, (1,), 1, (16, 16, 16, 16), ()): ("RGBA", "RGBA;16B"),\n (II, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16L"),\n (MM, 2, (1,), 1, (16, 16, 16, 16), (0,)): ("RGB", "RGBX;16B"),\n (II, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16L"),\n (MM, 2, (1,), 1, (16, 16, 16, 16), (1,)): ("RGBA", "RGBa;16B"),\n (II, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16L"),\n (MM, 2, (1,), 1, (16, 16, 16, 16), (2,)): ("RGBA", "RGBA;16B"),\n (II, 3, (1,), 1, (1,), ()): ("P", "P;1"),\n (MM, 3, (1,), 1, (1,), ()): ("P", "P;1"),\n (II, 3, (1,), 2, (1,), ()): ("P", "P;1R"),\n (MM, 3, (1,), 2, (1,), ()): ("P", "P;1R"),\n (II, 3, (1,), 1, (2,), ()): ("P", "P;2"),\n (MM, 3, (1,), 1, (2,), ()): ("P", "P;2"),\n (II, 3, (1,), 2, (2,), ()): ("P", "P;2R"),\n (MM, 3, (1,), 2, (2,), ()): ("P", "P;2R"),\n (II, 3, (1,), 1, (4,), ()): ("P", "P;4"),\n (MM, 3, (1,), 1, (4,), ()): ("P", "P;4"),\n (II, 3, (1,), 2, (4,), ()): ("P", "P;4R"),\n (MM, 3, (1,), 2, (4,), ()): ("P", "P;4R"),\n (II, 3, (1,), 1, (8,), ()): ("P", "P"),\n (MM, 3, (1,), 1, (8,), ()): ("P", "P"),\n (II, 3, (1,), 1, (8, 8), (0,)): ("P", "PX"),\n (II, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),\n (MM, 3, (1,), 1, (8, 8), (2,)): ("PA", "PA"),\n (II, 3, (1,), 2, (8,), ()): ("P", "P;R"),\n (MM, 3, (1,), 2, (8,), ()): ("P", "P;R"),\n (II, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),\n (MM, 5, (1,), 1, (8, 8, 8, 8), ()): ("CMYK", "CMYK"),\n (II, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),\n (MM, 5, (1,), 1, (8, 8, 8, 8, 8), (0,)): ("CMYK", "CMYKX"),\n (II, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),\n (MM, 5, (1,), 1, (8, 8, 8, 8, 8, 8), (0, 0)): ("CMYK", "CMYKXX"),\n (II, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16L"),\n (MM, 5, (1,), 1, (16, 16, 16, 16), ()): ("CMYK", "CMYK;16B"),\n (II, 6, (1,), 1, (8,), ()): ("L", "L"),\n (MM, 6, (1,), 1, (8,), ()): ("L", "L"),\n # JPEG compressed images handled by LibTiff and auto-converted to RGBX\n # Minimal Baseline TIFF requires YCbCr images to have 3 SamplesPerPixel\n (II, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),\n (MM, 6, (1,), 1, (8, 8, 8), ()): ("RGB", "RGBX"),\n (II, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),\n (MM, 8, (1,), 1, (8, 8, 8), ()): ("LAB", "LAB"),\n}\n\nMAX_SAMPLESPERPIXEL = max(len(key_tp[4]) for key_tp in OPEN_INFO)\n\nPREFIXES = [\n b"MM\x00\x2a", # Valid TIFF header with big-endian byte order\n b"II\x2a\x00", # Valid TIFF header with little-endian byte order\n b"MM\x2a\x00", # Invalid TIFF header, assume big-endian\n b"II\x00\x2a", # Invalid TIFF header, assume little-endian\n b"MM\x00\x2b", # BigTIFF with big-endian byte order\n b"II\x2b\x00", # BigTIFF with little-endian byte order\n]\n\nif not getattr(Image.core, "libtiff_support_custom_tags", True):\n deprecate("Support for LibTIFF earlier than version 4", 12)\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(tuple(PREFIXES))\n\n\ndef _limit_rational(\n val: float | Fraction | IFDRational, max_val: int\n) -> tuple[IntegralLike, IntegralLike]:\n inv = abs(val) > 1\n n_d = IFDRational(1 / val if inv else val).limit_rational(max_val)\n return n_d[::-1] if inv else n_d\n\n\ndef _limit_signed_rational(\n val: IFDRational, max_val: int, min_val: int\n) -> tuple[IntegralLike, IntegralLike]:\n frac = Fraction(val)\n n_d: tuple[IntegralLike, IntegralLike] = frac.numerator, frac.denominator\n\n if min(float(i) for i in n_d) < min_val:\n n_d = _limit_rational(val, abs(min_val))\n\n n_d_float = tuple(float(i) for i in n_d)\n if max(n_d_float) > max_val:\n n_d = _limit_rational(n_d_float[0] / n_d_float[1], max_val)\n\n return n_d\n\n\n##\n# Wrapper for TIFF IFDs.\n\n_load_dispatch = {}\n_write_dispatch = {}\n\n\ndef _delegate(op: str) -> Any:\n def delegate(\n self: IFDRational, *args: tuple[float, ...]\n ) -> bool | float | Fraction:\n return getattr(self._val, op)(*args)\n\n return delegate\n\n\nclass IFDRational(Rational):\n """Implements a rational class where 0/0 is a legal value to match\n the in the wild use of exif rationals.\n\n e.g., DigitalZoomRatio - 0.00/0.00 indicates that no digital zoom was used\n """\n\n """ If the denominator is 0, store this as a float('nan'), otherwise store\n as a fractions.Fraction(). Delegate as appropriate\n\n """\n\n __slots__ = ("_numerator", "_denominator", "_val")\n\n def __init__(\n self, value: float | Fraction | IFDRational, denominator: int = 1\n ) -> None:\n """\n :param value: either an integer numerator, a\n float/rational/other number, or an IFDRational\n :param denominator: Optional integer denominator\n """\n self._val: Fraction | float\n if isinstance(value, IFDRational):\n self._numerator = value.numerator\n self._denominator = value.denominator\n self._val = value._val\n return\n\n if isinstance(value, Fraction):\n self._numerator = value.numerator\n self._denominator = value.denominator\n else:\n if TYPE_CHECKING:\n self._numerator = cast(IntegralLike, value)\n else:\n self._numerator = value\n self._denominator = denominator\n\n if denominator == 0:\n self._val = float("nan")\n elif denominator == 1:\n self._val = Fraction(value)\n elif int(value) == value:\n self._val = Fraction(int(value), denominator)\n else:\n self._val = Fraction(value / denominator)\n\n @property\n def numerator(self) -> IntegralLike:\n return self._numerator\n\n @property\n def denominator(self) -> int:\n return self._denominator\n\n def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]:\n """\n\n :param max_denominator: Integer, the maximum denominator value\n :returns: Tuple of (numerator, denominator)\n """\n\n if self.denominator == 0:\n return self.numerator, self.denominator\n\n assert isinstance(self._val, Fraction)\n f = self._val.limit_denominator(max_denominator)\n return f.numerator, f.denominator\n\n def __repr__(self) -> str:\n return str(float(self._val))\n\n def __hash__(self) -> int: # type: ignore[override]\n return self._val.__hash__()\n\n def __eq__(self, other: object) -> bool:\n val = self._val\n if isinstance(other, IFDRational):\n other = other._val\n if isinstance(other, float):\n val = float(val)\n return val == other\n\n def __getstate__(self) -> list[float | Fraction | IntegralLike]:\n return [self._val, self._numerator, self._denominator]\n\n def __setstate__(self, state: list[float | Fraction | IntegralLike]) -> None:\n IFDRational.__init__(self, 0)\n _val, _numerator, _denominator = state\n assert isinstance(_val, (float, Fraction))\n self._val = _val\n if TYPE_CHECKING:\n self._numerator = cast(IntegralLike, _numerator)\n else:\n self._numerator = _numerator\n assert isinstance(_denominator, int)\n self._denominator = _denominator\n\n """ a = ['add','radd', 'sub', 'rsub', 'mul', 'rmul',\n 'truediv', 'rtruediv', 'floordiv', 'rfloordiv',\n 'mod','rmod', 'pow','rpow', 'pos', 'neg',\n 'abs', 'trunc', 'lt', 'gt', 'le', 'ge', 'bool',\n 'ceil', 'floor', 'round']\n print("\n".join("__%s__ = _delegate('__%s__')" % (s,s) for s in a))\n """\n\n __add__ = _delegate("__add__")\n __radd__ = _delegate("__radd__")\n __sub__ = _delegate("__sub__")\n __rsub__ = _delegate("__rsub__")\n __mul__ = _delegate("__mul__")\n __rmul__ = _delegate("__rmul__")\n __truediv__ = _delegate("__truediv__")\n __rtruediv__ = _delegate("__rtruediv__")\n __floordiv__ = _delegate("__floordiv__")\n __rfloordiv__ = _delegate("__rfloordiv__")\n __mod__ = _delegate("__mod__")\n __rmod__ = _delegate("__rmod__")\n __pow__ = _delegate("__pow__")\n __rpow__ = _delegate("__rpow__")\n __pos__ = _delegate("__pos__")\n __neg__ = _delegate("__neg__")\n __abs__ = _delegate("__abs__")\n __trunc__ = _delegate("__trunc__")\n __lt__ = _delegate("__lt__")\n __gt__ = _delegate("__gt__")\n __le__ = _delegate("__le__")\n __ge__ = _delegate("__ge__")\n __bool__ = _delegate("__bool__")\n __ceil__ = _delegate("__ceil__")\n __floor__ = _delegate("__floor__")\n __round__ = _delegate("__round__")\n # Python >= 3.11\n if hasattr(Fraction, "__int__"):\n __int__ = _delegate("__int__")\n\n\n_LoaderFunc = Callable[["ImageFileDirectory_v2", bytes, bool], Any]\n\n\ndef _register_loader(idx: int, size: int) -> Callable[[_LoaderFunc], _LoaderFunc]:\n def decorator(func: _LoaderFunc) -> _LoaderFunc:\n from .TiffTags import TYPES\n\n if func.__name__.startswith("load_"):\n TYPES[idx] = func.__name__[5:].replace("_", " ")\n _load_dispatch[idx] = size, func # noqa: F821\n return func\n\n return decorator\n\n\ndef _register_writer(idx: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:\n def decorator(func: Callable[..., Any]) -> Callable[..., Any]:\n _write_dispatch[idx] = func # noqa: F821\n return func\n\n return decorator\n\n\ndef _register_basic(idx_fmt_name: tuple[int, str, str]) -> None:\n from .TiffTags import TYPES\n\n idx, fmt, name = idx_fmt_name\n TYPES[idx] = name\n size = struct.calcsize(f"={fmt}")\n\n def basic_handler(\n self: ImageFileDirectory_v2, data: bytes, legacy_api: bool = True\n ) -> tuple[Any, ...]:\n return self._unpack(f"{len(data) // size}{fmt}", data)\n\n _load_dispatch[idx] = size, basic_handler # noqa: F821\n _write_dispatch[idx] = lambda self, *values: ( # noqa: F821\n b"".join(self._pack(fmt, value) for value in values)\n )\n\n\nif TYPE_CHECKING:\n _IFDv2Base = MutableMapping[int, Any]\nelse:\n _IFDv2Base = MutableMapping\n\n\nclass ImageFileDirectory_v2(_IFDv2Base):\n """This class represents a TIFF tag directory. To speed things up, we\n don't decode tags unless they're asked for.\n\n Exposes a dictionary interface of the tags in the directory::\n\n ifd = ImageFileDirectory_v2()\n ifd[key] = 'Some Data'\n ifd.tagtype[key] = TiffTags.ASCII\n print(ifd[key])\n 'Some Data'\n\n Individual values are returned as the strings or numbers, sequences are\n returned as tuples of the values.\n\n The tiff metadata type of each item is stored in a dictionary of\n tag types in\n :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v2.tagtype`. The types\n are read from a tiff file, guessed from the type added, or added\n manually.\n\n Data Structures:\n\n * ``self.tagtype = {}``\n\n * Key: numerical TIFF tag number\n * Value: integer corresponding to the data type from\n :py:data:`.TiffTags.TYPES`\n\n .. versionadded:: 3.0.0\n\n 'Internal' data structures:\n\n * ``self._tags_v2 = {}``\n\n * Key: numerical TIFF tag number\n * Value: decoded data, as tuple for multiple values\n\n * ``self._tagdata = {}``\n\n * Key: numerical TIFF tag number\n * Value: undecoded byte string from file\n\n * ``self._tags_v1 = {}``\n\n * Key: numerical TIFF tag number\n * Value: decoded data in the v1 format\n\n Tags will be found in the private attributes ``self._tagdata``, and in\n ``self._tags_v2`` once decoded.\n\n ``self.legacy_api`` is a value for internal use, and shouldn't be changed\n from outside code. In cooperation with\n :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`, if ``legacy_api``\n is true, then decoded tags will be populated into both ``_tags_v1`` and\n ``_tags_v2``. ``_tags_v2`` will be used if this IFD is used in the TIFF\n save routine. Tags should be read from ``_tags_v1`` if\n ``legacy_api == true``.\n\n """\n\n _load_dispatch: dict[int, tuple[int, _LoaderFunc]] = {}\n _write_dispatch: dict[int, Callable[..., Any]] = {}\n\n def __init__(\n self,\n ifh: bytes = b"II\x2a\x00\x00\x00\x00\x00",\n prefix: bytes | None = None,\n group: int | None = None,\n ) -> None:\n """Initialize an ImageFileDirectory.\n\n To construct an ImageFileDirectory from a real file, pass the 8-byte\n magic header to the constructor. To only set the endianness, pass it\n as the 'prefix' keyword argument.\n\n :param ifh: One of the accepted magic headers (cf. PREFIXES); also sets\n endianness.\n :param prefix: Override the endianness of the file.\n """\n if not _accept(ifh):\n msg = f"not a TIFF file (header {repr(ifh)} not valid)"\n raise SyntaxError(msg)\n self._prefix = prefix if prefix is not None else ifh[:2]\n if self._prefix == MM:\n self._endian = ">"\n elif self._prefix == II:\n self._endian = "<"\n else:\n msg = "not a TIFF IFD"\n raise SyntaxError(msg)\n self._bigtiff = ifh[2] == 43\n self.group = group\n self.tagtype: dict[int, int] = {}\n """ Dictionary of tag types """\n self.reset()\n self.next = (\n self._unpack("Q", ifh[8:])[0]\n if self._bigtiff\n else self._unpack("L", ifh[4:])[0]\n )\n self._legacy_api = False\n\n prefix = property(lambda self: self._prefix)\n offset = property(lambda self: self._offset)\n\n @property\n def legacy_api(self) -> bool:\n return self._legacy_api\n\n @legacy_api.setter\n def legacy_api(self, value: bool) -> NoReturn:\n msg = "Not allowing setting of legacy api"\n raise Exception(msg)\n\n def reset(self) -> None:\n self._tags_v1: dict[int, Any] = {} # will remain empty if legacy_api is false\n self._tags_v2: dict[int, Any] = {} # main tag storage\n self._tagdata: dict[int, bytes] = {}\n self.tagtype = {} # added 2008-06-05 by Florian Hoech\n self._next = None\n self._offset: int | None = None\n\n def __str__(self) -> str:\n return str(dict(self))\n\n def named(self) -> dict[str, Any]:\n """\n :returns: dict of name|key: value\n\n Returns the complete tag dictionary, with named tags where possible.\n """\n return {\n TiffTags.lookup(code, self.group).name: value\n for code, value in self.items()\n }\n\n def __len__(self) -> int:\n return len(set(self._tagdata) | set(self._tags_v2))\n\n def __getitem__(self, tag: int) -> Any:\n if tag not in self._tags_v2: # unpack on the fly\n data = self._tagdata[tag]\n typ = self.tagtype[tag]\n size, handler = self._load_dispatch[typ]\n self[tag] = handler(self, data, self.legacy_api) # check type\n val = self._tags_v2[tag]\n if self.legacy_api and not isinstance(val, (tuple, bytes)):\n val = (val,)\n return val\n\n def __contains__(self, tag: object) -> bool:\n return tag in self._tags_v2 or tag in self._tagdata\n\n def __setitem__(self, tag: int, value: Any) -> None:\n self._setitem(tag, value, self.legacy_api)\n\n def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None:\n basetypes = (Number, bytes, str)\n\n info = TiffTags.lookup(tag, self.group)\n values = [value] if isinstance(value, basetypes) else value\n\n if tag not in self.tagtype:\n if info.type:\n self.tagtype[tag] = info.type\n else:\n self.tagtype[tag] = TiffTags.UNDEFINED\n if all(isinstance(v, IFDRational) for v in values):\n for v in values:\n assert isinstance(v, IFDRational)\n if v < 0:\n self.tagtype[tag] = TiffTags.SIGNED_RATIONAL\n break\n else:\n self.tagtype[tag] = TiffTags.RATIONAL\n elif all(isinstance(v, int) for v in values):\n short = True\n signed_short = True\n long = True\n for v in values:\n assert isinstance(v, int)\n if short and not (0 <= v < 2**16):\n short = False\n if signed_short and not (-(2**15) < v < 2**15):\n signed_short = False\n if long and v < 0:\n long = False\n if short:\n self.tagtype[tag] = TiffTags.SHORT\n elif signed_short:\n self.tagtype[tag] = TiffTags.SIGNED_SHORT\n elif long:\n self.tagtype[tag] = TiffTags.LONG\n else:\n self.tagtype[tag] = TiffTags.SIGNED_LONG\n elif all(isinstance(v, float) for v in values):\n self.tagtype[tag] = TiffTags.DOUBLE\n elif all(isinstance(v, str) for v in values):\n self.tagtype[tag] = TiffTags.ASCII\n elif all(isinstance(v, bytes) for v in values):\n self.tagtype[tag] = TiffTags.BYTE\n\n if self.tagtype[tag] == TiffTags.UNDEFINED:\n values = [\n v.encode("ascii", "replace") if isinstance(v, str) else v\n for v in values\n ]\n elif self.tagtype[tag] == TiffTags.RATIONAL:\n values = [float(v) if isinstance(v, int) else v for v in values]\n\n is_ifd = self.tagtype[tag] == TiffTags.LONG and isinstance(values, dict)\n if not is_ifd:\n values = tuple(\n info.cvt_enum(value) if isinstance(value, str) else value\n for value in values\n )\n\n dest = self._tags_v1 if legacy_api else self._tags_v2\n\n # Three branches:\n # Spec'd length == 1, Actual length 1, store as element\n # Spec'd length == 1, Actual > 1, Warn and truncate. Formerly barfed.\n # No Spec, Actual length 1, Formerly (<4.2) returned a 1 element tuple.\n # Don't mess with the legacy api, since it's frozen.\n if not is_ifd and (\n (info.length == 1)\n or self.tagtype[tag] == TiffTags.BYTE\n or (info.length is None and len(values) == 1 and not legacy_api)\n ):\n # Don't mess with the legacy api, since it's frozen.\n if legacy_api and self.tagtype[tag] in [\n TiffTags.RATIONAL,\n TiffTags.SIGNED_RATIONAL,\n ]: # rationals\n values = (values,)\n try:\n (dest[tag],) = values\n except ValueError:\n # We've got a builtin tag with 1 expected entry\n warnings.warn(\n f"Metadata Warning, tag {tag} had too many entries: "\n f"{len(values)}, expected 1"\n )\n dest[tag] = values[0]\n\n else:\n # Spec'd length > 1 or undefined\n # Unspec'd, and length > 1\n dest[tag] = values\n\n def __delitem__(self, tag: int) -> None:\n self._tags_v2.pop(tag, None)\n self._tags_v1.pop(tag, None)\n self._tagdata.pop(tag, None)\n\n def __iter__(self) -> Iterator[int]:\n return iter(set(self._tagdata) | set(self._tags_v2))\n\n def _unpack(self, fmt: str, data: bytes) -> tuple[Any, ...]:\n return struct.unpack(self._endian + fmt, data)\n\n def _pack(self, fmt: str, *values: Any) -> bytes:\n return struct.pack(self._endian + fmt, *values)\n\n list(\n map(\n _register_basic,\n [\n (TiffTags.SHORT, "H", "short"),\n (TiffTags.LONG, "L", "long"),\n (TiffTags.SIGNED_BYTE, "b", "signed byte"),\n (TiffTags.SIGNED_SHORT, "h", "signed short"),\n (TiffTags.SIGNED_LONG, "l", "signed long"),\n (TiffTags.FLOAT, "f", "float"),\n (TiffTags.DOUBLE, "d", "double"),\n (TiffTags.IFD, "L", "long"),\n (TiffTags.LONG8, "Q", "long8"),\n ],\n )\n )\n\n @_register_loader(1, 1) # Basic type, except for the legacy API.\n def load_byte(self, data: bytes, legacy_api: bool = True) -> bytes:\n return data\n\n @_register_writer(1) # Basic type, except for the legacy API.\n def write_byte(self, data: bytes | int | IFDRational) -> bytes:\n if isinstance(data, IFDRational):\n data = int(data)\n if isinstance(data, int):\n data = bytes((data,))\n return data\n\n @_register_loader(2, 1)\n def load_string(self, data: bytes, legacy_api: bool = True) -> str:\n if data.endswith(b"\0"):\n data = data[:-1]\n return data.decode("latin-1", "replace")\n\n @_register_writer(2)\n def write_string(self, value: str | bytes | int) -> bytes:\n # remerge of https://github.com/python-pillow/Pillow/pull/1416\n if isinstance(value, int):\n value = str(value)\n if not isinstance(value, bytes):\n value = value.encode("ascii", "replace")\n return value + b"\0"\n\n @_register_loader(5, 8)\n def load_rational(\n self, data: bytes, legacy_api: bool = True\n ) -> tuple[tuple[int, int] | IFDRational, ...]:\n vals = self._unpack(f"{len(data) // 4}L", data)\n\n def combine(a: int, b: int) -> tuple[int, int] | IFDRational:\n return (a, b) if legacy_api else IFDRational(a, b)\n\n return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))\n\n @_register_writer(5)\n def write_rational(self, *values: IFDRational) -> bytes:\n return b"".join(\n self._pack("2L", *_limit_rational(frac, 2**32 - 1)) for frac in values\n )\n\n @_register_loader(7, 1)\n def load_undefined(self, data: bytes, legacy_api: bool = True) -> bytes:\n return data\n\n @_register_writer(7)\n def write_undefined(self, value: bytes | int | IFDRational) -> bytes:\n if isinstance(value, IFDRational):\n value = int(value)\n if isinstance(value, int):\n value = str(value).encode("ascii", "replace")\n return value\n\n @_register_loader(10, 8)\n def load_signed_rational(\n self, data: bytes, legacy_api: bool = True\n ) -> tuple[tuple[int, int] | IFDRational, ...]:\n vals = self._unpack(f"{len(data) // 4}l", data)\n\n def combine(a: int, b: int) -> tuple[int, int] | IFDRational:\n return (a, b) if legacy_api else IFDRational(a, b)\n\n return tuple(combine(num, denom) for num, denom in zip(vals[::2], vals[1::2]))\n\n @_register_writer(10)\n def write_signed_rational(self, *values: IFDRational) -> bytes:\n return b"".join(\n self._pack("2l", *_limit_signed_rational(frac, 2**31 - 1, -(2**31)))\n for frac in values\n )\n\n def _ensure_read(self, fp: IO[bytes], size: int) -> bytes:\n ret = fp.read(size)\n if len(ret) != size:\n msg = (\n "Corrupt EXIF data. "\n f"Expecting to read {size} bytes but only got {len(ret)}. "\n )\n raise OSError(msg)\n return ret\n\n def load(self, fp: IO[bytes]) -> None:\n self.reset()\n self._offset = fp.tell()\n\n try:\n tag_count = (\n self._unpack("Q", self._ensure_read(fp, 8))\n if self._bigtiff\n else self._unpack("H", self._ensure_read(fp, 2))\n )[0]\n for i in range(tag_count):\n tag, typ, count, data = (\n self._unpack("HHQ8s", self._ensure_read(fp, 20))\n if self._bigtiff\n else self._unpack("HHL4s", self._ensure_read(fp, 12))\n )\n\n tagname = TiffTags.lookup(tag, self.group).name\n typname = TYPES.get(typ, "unknown")\n msg = f"tag: {tagname} ({tag}) - type: {typname} ({typ})"\n\n try:\n unit_size, handler = self._load_dispatch[typ]\n except KeyError:\n logger.debug("%s - unsupported type %s", msg, typ)\n continue # ignore unsupported type\n size = count * unit_size\n if size > (8 if self._bigtiff else 4):\n here = fp.tell()\n (offset,) = self._unpack("Q" if self._bigtiff else "L", data)\n msg += f" Tag Location: {here} - Data Location: {offset}"\n fp.seek(offset)\n data = ImageFile._safe_read(fp, size)\n fp.seek(here)\n else:\n data = data[:size]\n\n if len(data) != size:\n warnings.warn(\n "Possibly corrupt EXIF data. "\n f"Expecting to read {size} bytes but only got {len(data)}."\n f" Skipping tag {tag}"\n )\n logger.debug(msg)\n continue\n\n if not data:\n logger.debug(msg)\n continue\n\n self._tagdata[tag] = data\n self.tagtype[tag] = typ\n\n msg += " - value: "\n msg += f"<table: {size} bytes>" if size > 32 else repr(data)\n\n logger.debug(msg)\n\n (self.next,) = (\n self._unpack("Q", self._ensure_read(fp, 8))\n if self._bigtiff\n else self._unpack("L", self._ensure_read(fp, 4))\n )\n except OSError as msg:\n warnings.warn(str(msg))\n return\n\n def _get_ifh(self) -> bytes:\n ifh = self._prefix + self._pack("H", 43 if self._bigtiff else 42)\n if self._bigtiff:\n ifh += self._pack("HH", 8, 0)\n ifh += self._pack("Q", 16) if self._bigtiff else self._pack("L", 8)\n\n return ifh\n\n def tobytes(self, offset: int = 0) -> bytes:\n # FIXME What about tagdata?\n result = self._pack("Q" if self._bigtiff else "H", len(self._tags_v2))\n\n entries: list[tuple[int, int, int, bytes, bytes]] = []\n\n fmt = "Q" if self._bigtiff else "L"\n fmt_size = 8 if self._bigtiff else 4\n offset += (\n len(result) + len(self._tags_v2) * (20 if self._bigtiff else 12) + fmt_size\n )\n stripoffsets = None\n\n # pass 1: convert tags to binary format\n # always write tags in ascending order\n for tag, value in sorted(self._tags_v2.items()):\n if tag == STRIPOFFSETS:\n stripoffsets = len(entries)\n typ = self.tagtype[tag]\n logger.debug("Tag %s, Type: %s, Value: %s", tag, typ, repr(value))\n is_ifd = typ == TiffTags.LONG and isinstance(value, dict)\n if is_ifd:\n ifd = ImageFileDirectory_v2(self._get_ifh(), group=tag)\n values = self._tags_v2[tag]\n for ifd_tag, ifd_value in values.items():\n ifd[ifd_tag] = ifd_value\n data = ifd.tobytes(offset)\n else:\n values = value if isinstance(value, tuple) else (value,)\n data = self._write_dispatch[typ](self, *values)\n\n tagname = TiffTags.lookup(tag, self.group).name\n typname = "ifd" if is_ifd else TYPES.get(typ, "unknown")\n msg = f"save: {tagname} ({tag}) - type: {typname} ({typ}) - value: "\n msg += f"<table: {len(data)} bytes>" if len(data) >= 16 else str(values)\n logger.debug(msg)\n\n # count is sum of lengths for string and arbitrary data\n if is_ifd:\n count = 1\n elif typ in [TiffTags.BYTE, TiffTags.ASCII, TiffTags.UNDEFINED]:\n count = len(data)\n else:\n count = len(values)\n # figure out if data fits into the entry\n if len(data) <= fmt_size:\n entries.append((tag, typ, count, data.ljust(fmt_size, b"\0"), b""))\n else:\n entries.append((tag, typ, count, self._pack(fmt, offset), data))\n offset += (len(data) + 1) // 2 * 2 # pad to word\n\n # update strip offset data to point beyond auxiliary data\n if stripoffsets is not None:\n tag, typ, count, value, data = entries[stripoffsets]\n if data:\n size, handler = self._load_dispatch[typ]\n values = [val + offset for val in handler(self, data, self.legacy_api)]\n data = self._write_dispatch[typ](self, *values)\n else:\n value = self._pack(fmt, self._unpack(fmt, value)[0] + offset)\n entries[stripoffsets] = tag, typ, count, value, data\n\n # pass 2: write entries to file\n for tag, typ, count, value, data in entries:\n logger.debug("%s %s %s %s %s", tag, typ, count, repr(value), repr(data))\n result += self._pack(\n "HHQ8s" if self._bigtiff else "HHL4s", tag, typ, count, value\n )\n\n # -- overwrite here for multi-page --\n result += self._pack(fmt, 0) # end of entries\n\n # pass 3: write auxiliary data to file\n for tag, typ, count, value, data in entries:\n result += data\n if len(data) & 1:\n result += b"\0"\n\n return result\n\n def save(self, fp: IO[bytes]) -> int:\n if fp.tell() == 0: # skip TIFF header on subsequent pages\n fp.write(self._get_ifh())\n\n offset = fp.tell()\n result = self.tobytes(offset)\n fp.write(result)\n return offset + len(result)\n\n\nImageFileDirectory_v2._load_dispatch = _load_dispatch\nImageFileDirectory_v2._write_dispatch = _write_dispatch\nfor idx, name in TYPES.items():\n name = name.replace(" ", "_")\n setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1])\n setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx])\ndel _load_dispatch, _write_dispatch, idx, name\n\n\n# Legacy ImageFileDirectory support.\nclass ImageFileDirectory_v1(ImageFileDirectory_v2):\n """This class represents the **legacy** interface to a TIFF tag directory.\n\n Exposes a dictionary interface of the tags in the directory::\n\n ifd = ImageFileDirectory_v1()\n ifd[key] = 'Some Data'\n ifd.tagtype[key] = TiffTags.ASCII\n print(ifd[key])\n ('Some Data',)\n\n Also contains a dictionary of tag types as read from the tiff image file,\n :attr:`~PIL.TiffImagePlugin.ImageFileDirectory_v1.tagtype`.\n\n Values are returned as a tuple.\n\n .. deprecated:: 3.0.0\n """\n\n def __init__(self, *args: Any, **kwargs: Any) -> None:\n super().__init__(*args, **kwargs)\n self._legacy_api = True\n\n tags = property(lambda self: self._tags_v1)\n tagdata = property(lambda self: self._tagdata)\n\n # defined in ImageFileDirectory_v2\n tagtype: dict[int, int]\n """Dictionary of tag types"""\n\n @classmethod\n def from_v2(cls, original: ImageFileDirectory_v2) -> ImageFileDirectory_v1:\n """Returns an\n :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n instance with the same data as is contained in the original\n :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n instance.\n\n :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n\n """\n\n ifd = cls(prefix=original.prefix)\n ifd._tagdata = original._tagdata\n ifd.tagtype = original.tagtype\n ifd.next = original.next # an indicator for multipage tiffs\n return ifd\n\n def to_v2(self) -> ImageFileDirectory_v2:\n """Returns an\n :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n instance with the same data as is contained in the original\n :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v1`\n instance.\n\n :returns: :py:class:`~PIL.TiffImagePlugin.ImageFileDirectory_v2`\n\n """\n\n ifd = ImageFileDirectory_v2(prefix=self.prefix)\n ifd._tagdata = dict(self._tagdata)\n ifd.tagtype = dict(self.tagtype)\n ifd._tags_v2 = dict(self._tags_v2)\n return ifd\n\n def __contains__(self, tag: object) -> bool:\n return tag in self._tags_v1 or tag in self._tagdata\n\n def __len__(self) -> int:\n return len(set(self._tagdata) | set(self._tags_v1))\n\n def __iter__(self) -> Iterator[int]:\n return iter(set(self._tagdata) | set(self._tags_v1))\n\n def __setitem__(self, tag: int, value: Any) -> None:\n for legacy_api in (False, True):\n self._setitem(tag, value, legacy_api)\n\n def __getitem__(self, tag: int) -> Any:\n if tag not in self._tags_v1: # unpack on the fly\n data = self._tagdata[tag]\n typ = self.tagtype[tag]\n size, handler = self._load_dispatch[typ]\n for legacy in (False, True):\n self._setitem(tag, handler(self, data, legacy), legacy)\n val = self._tags_v1[tag]\n if not isinstance(val, (tuple, bytes)):\n val = (val,)\n return val\n\n\n# undone -- switch this pointer\nImageFileDirectory = ImageFileDirectory_v1\n\n\n##\n# Image plugin for TIFF files.\n\n\nclass TiffImageFile(ImageFile.ImageFile):\n format = "TIFF"\n format_description = "Adobe TIFF"\n _close_exclusive_fp_after_loading = False\n\n def __init__(\n self,\n fp: StrOrBytesPath | IO[bytes],\n filename: str | bytes | None = None,\n ) -> None:\n self.tag_v2: ImageFileDirectory_v2\n """ Image file directory (tag dictionary) """\n\n self.tag: ImageFileDirectory_v1\n """ Legacy tag entries """\n\n super().__init__(fp, filename)\n\n def _open(self) -> None:\n """Open the first image in a TIFF file"""\n\n # Header\n ifh = self.fp.read(8)\n if ifh[2] == 43:\n ifh += self.fp.read(8)\n\n self.tag_v2 = ImageFileDirectory_v2(ifh)\n\n # setup frame pointers\n self.__first = self.__next = self.tag_v2.next\n self.__frame = -1\n self._fp = self.fp\n self._frame_pos: list[int] = []\n self._n_frames: int | None = None\n\n logger.debug("*** TiffImageFile._open ***")\n logger.debug("- __first: %s", self.__first)\n logger.debug("- ifh: %s", repr(ifh)) # Use repr to avoid str(bytes)\n\n # and load the first frame\n self._seek(0)\n\n @property\n def n_frames(self) -> int:\n current_n_frames = self._n_frames\n if current_n_frames is None:\n current = self.tell()\n self._seek(len(self._frame_pos))\n while self._n_frames is None:\n self._seek(self.tell() + 1)\n self.seek(current)\n assert self._n_frames is not None\n return self._n_frames\n\n def seek(self, frame: int) -> None:\n """Select a given frame as current image"""\n if not self._seek_check(frame):\n return\n self._seek(frame)\n if self._im is not None and (\n self.im.size != self._tile_size\n or self.im.mode != self.mode\n or self.readonly\n ):\n self._im = None\n\n def _seek(self, frame: int) -> None:\n if isinstance(self._fp, DeferredError):\n raise self._fp.ex\n self.fp = self._fp\n\n while len(self._frame_pos) <= frame:\n if not self.__next:\n msg = "no more images in TIFF file"\n raise EOFError(msg)\n logger.debug(\n "Seeking to frame %s, on frame %s, __next %s, location: %s",\n frame,\n self.__frame,\n self.__next,\n self.fp.tell(),\n )\n if self.__next >= 2**63:\n msg = "Unable to seek to frame"\n raise ValueError(msg)\n self.fp.seek(self.__next)\n self._frame_pos.append(self.__next)\n logger.debug("Loading tags, location: %s", self.fp.tell())\n self.tag_v2.load(self.fp)\n if self.tag_v2.next in self._frame_pos:\n # This IFD has already been processed\n # Declare this to be the end of the image\n self.__next = 0\n else:\n self.__next = self.tag_v2.next\n if self.__next == 0:\n self._n_frames = frame + 1\n if len(self._frame_pos) == 1:\n self.is_animated = self.__next != 0\n self.__frame += 1\n self.fp.seek(self._frame_pos[frame])\n self.tag_v2.load(self.fp)\n if XMP in self.tag_v2:\n xmp = self.tag_v2[XMP]\n if isinstance(xmp, tuple) and len(xmp) == 1:\n xmp = xmp[0]\n self.info["xmp"] = xmp\n elif "xmp" in self.info:\n del self.info["xmp"]\n self._reload_exif()\n # fill the legacy tag/ifd entries\n self.tag = self.ifd = ImageFileDirectory_v1.from_v2(self.tag_v2)\n self.__frame = frame\n self._setup()\n\n def tell(self) -> int:\n """Return the current frame number"""\n return self.__frame\n\n def get_photoshop_blocks(self) -> dict[int, dict[str, bytes]]:\n """\n Returns a dictionary of Photoshop "Image Resource Blocks".\n The keys are the image resource ID. For more information, see\n https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037727\n\n :returns: Photoshop "Image Resource Blocks" in a dictionary.\n """\n blocks = {}\n val = self.tag_v2.get(ExifTags.Base.ImageResources)\n if val:\n while val.startswith(b"8BIM"):\n id = i16(val[4:6])\n n = math.ceil((val[6] + 1) / 2) * 2\n size = i32(val[6 + n : 10 + n])\n data = val[10 + n : 10 + n + size]\n blocks[id] = {"data": data}\n\n val = val[math.ceil((10 + n + size) / 2) * 2 :]\n return blocks\n\n def load(self) -> Image.core.PixelAccess | None:\n if self.tile and self.use_load_libtiff:\n return self._load_libtiff()\n return super().load()\n\n def load_prepare(self) -> None:\n if self._im is None:\n Image._decompression_bomb_check(self._tile_size)\n self.im = Image.core.new(self.mode, self._tile_size)\n ImageFile.ImageFile.load_prepare(self)\n\n def load_end(self) -> None:\n # allow closing if we're on the first frame, there's no next\n # This is the ImageFile.load path only, libtiff specific below.\n if not self.is_animated:\n self._close_exclusive_fp_after_loading = True\n\n # load IFD data from fp before it is closed\n exif = self.getexif()\n for key in TiffTags.TAGS_V2_GROUPS:\n if key not in exif:\n continue\n exif.get_ifd(key)\n\n ImageOps.exif_transpose(self, in_place=True)\n if ExifTags.Base.Orientation in self.tag_v2:\n del self.tag_v2[ExifTags.Base.Orientation]\n\n def _load_libtiff(self) -> Image.core.PixelAccess | None:\n """Overload method triggered when we detect a compressed tiff\n Calls out to libtiff"""\n\n Image.Image.load(self)\n\n self.load_prepare()\n\n if not len(self.tile) == 1:\n msg = "Not exactly one tile"\n raise OSError(msg)\n\n # (self._compression, (extents tuple),\n # 0, (rawmode, self._compression, fp))\n extents = self.tile[0][1]\n args = self.tile[0][3]\n\n # To be nice on memory footprint, if there's a\n # file descriptor, use that instead of reading\n # into a string in python.\n try:\n fp = hasattr(self.fp, "fileno") and self.fp.fileno()\n # flush the file descriptor, prevents error on pypy 2.4+\n # should also eliminate the need for fp.tell\n # in _seek\n if hasattr(self.fp, "flush"):\n self.fp.flush()\n except OSError:\n # io.BytesIO have a fileno, but returns an OSError if\n # it doesn't use a file descriptor.\n fp = False\n\n if fp:\n assert isinstance(args, tuple)\n args_list = list(args)\n args_list[2] = fp\n args = tuple(args_list)\n\n decoder = Image._getdecoder(self.mode, "libtiff", args, self.decoderconfig)\n try:\n decoder.setimage(self.im, extents)\n except ValueError as e:\n msg = "Couldn't set the image"\n raise OSError(msg) from e\n\n close_self_fp = self._exclusive_fp and not self.is_animated\n if hasattr(self.fp, "getvalue"):\n # We've got a stringio like thing passed in. Yay for all in memory.\n # The decoder needs the entire file in one shot, so there's not\n # a lot we can do here other than give it the entire file.\n # unless we could do something like get the address of the\n # underlying string for stringio.\n #\n # Rearranging for supporting byteio items, since they have a fileno\n # that returns an OSError if there's no underlying fp. Easier to\n # deal with here by reordering.\n logger.debug("have getvalue. just sending in a string from getvalue")\n n, err = decoder.decode(self.fp.getvalue())\n elif fp:\n # we've got a actual file on disk, pass in the fp.\n logger.debug("have fileno, calling fileno version of the decoder.")\n if not close_self_fp:\n self.fp.seek(0)\n # Save and restore the file position, because libtiff will move it\n # outside of the Python runtime, and that will confuse\n # io.BufferedReader and possible others.\n # NOTE: This must use os.lseek(), and not fp.tell()/fp.seek(),\n # because the buffer read head already may not equal the actual\n # file position, and fp.seek() may just adjust it's internal\n # pointer and not actually seek the OS file handle.\n pos = os.lseek(fp, 0, os.SEEK_CUR)\n # 4 bytes, otherwise the trace might error out\n n, err = decoder.decode(b"fpfp")\n os.lseek(fp, pos, os.SEEK_SET)\n else:\n # we have something else.\n logger.debug("don't have fileno or getvalue. just reading")\n self.fp.seek(0)\n # UNDONE -- so much for that buffer size thing.\n n, err = decoder.decode(self.fp.read())\n\n self.tile = []\n self.readonly = 0\n\n self.load_end()\n\n if close_self_fp:\n self.fp.close()\n self.fp = None # might be shared\n\n if err < 0:\n msg = f"decoder error {err}"\n raise OSError(msg)\n\n return Image.Image.load(self)\n\n def _setup(self) -> None:\n """Setup this image object based on current tags"""\n\n if 0xBC01 in self.tag_v2:\n msg = "Windows Media Photo files not yet supported"\n raise OSError(msg)\n\n # extract relevant tags\n self._compression = COMPRESSION_INFO[self.tag_v2.get(COMPRESSION, 1)]\n self._planar_configuration = self.tag_v2.get(PLANAR_CONFIGURATION, 1)\n\n # photometric is a required tag, but not everyone is reading\n # the specification\n photo = self.tag_v2.get(PHOTOMETRIC_INTERPRETATION, 0)\n\n # old style jpeg compression images most certainly are YCbCr\n if self._compression == "tiff_jpeg":\n photo = 6\n\n fillorder = self.tag_v2.get(FILLORDER, 1)\n\n logger.debug("*** Summary ***")\n logger.debug("- compression: %s", self._compression)\n logger.debug("- photometric_interpretation: %s", photo)\n logger.debug("- planar_configuration: %s", self._planar_configuration)\n logger.debug("- fill_order: %s", fillorder)\n logger.debug("- YCbCr subsampling: %s", self.tag_v2.get(YCBCRSUBSAMPLING))\n\n # size\n try:\n xsize = self.tag_v2[IMAGEWIDTH]\n ysize = self.tag_v2[IMAGELENGTH]\n except KeyError as e:\n msg = "Missing dimensions"\n raise TypeError(msg) from e\n if not isinstance(xsize, int) or not isinstance(ysize, int):\n msg = "Invalid dimensions"\n raise ValueError(msg)\n self._tile_size = xsize, ysize\n orientation = self.tag_v2.get(ExifTags.Base.Orientation)\n if orientation in (5, 6, 7, 8):\n self._size = ysize, xsize\n else:\n self._size = xsize, ysize\n\n logger.debug("- size: %s", self.size)\n\n sample_format = self.tag_v2.get(SAMPLEFORMAT, (1,))\n if len(sample_format) > 1 and max(sample_format) == min(sample_format) == 1:\n # SAMPLEFORMAT is properly per band, so an RGB image will\n # be (1,1,1). But, we don't support per band pixel types,\n # and anything more than one band is a uint8. So, just\n # take the first element. Revisit this if adding support\n # for more exotic images.\n sample_format = (1,)\n\n bps_tuple = self.tag_v2.get(BITSPERSAMPLE, (1,))\n extra_tuple = self.tag_v2.get(EXTRASAMPLES, ())\n if photo in (2, 6, 8): # RGB, YCbCr, LAB\n bps_count = 3\n elif photo == 5: # CMYK\n bps_count = 4\n else:\n bps_count = 1\n bps_count += len(extra_tuple)\n bps_actual_count = len(bps_tuple)\n samples_per_pixel = self.tag_v2.get(\n SAMPLESPERPIXEL,\n 3 if self._compression == "tiff_jpeg" and photo in (2, 6) else 1,\n )\n\n if samples_per_pixel > MAX_SAMPLESPERPIXEL:\n # DOS check, samples_per_pixel can be a Long, and we extend the tuple below\n logger.error(\n "More samples per pixel than can be decoded: %s", samples_per_pixel\n )\n msg = "Invalid value for samples per pixel"\n raise SyntaxError(msg)\n\n if samples_per_pixel < bps_actual_count:\n # If a file has more values in bps_tuple than expected,\n # remove the excess.\n bps_tuple = bps_tuple[:samples_per_pixel]\n elif samples_per_pixel > bps_actual_count and bps_actual_count == 1:\n # If a file has only one value in bps_tuple, when it should have more,\n # presume it is the same number of bits for all of the samples.\n bps_tuple = bps_tuple * samples_per_pixel\n\n if len(bps_tuple) != samples_per_pixel:\n msg = "unknown data organization"\n raise SyntaxError(msg)\n\n # mode: check photometric interpretation and bits per pixel\n key = (\n self.tag_v2.prefix,\n photo,\n sample_format,\n fillorder,\n bps_tuple,\n extra_tuple,\n )\n logger.debug("format key: %s", key)\n try:\n self._mode, rawmode = OPEN_INFO[key]\n except KeyError as e:\n logger.debug("- unsupported format")\n msg = "unknown pixel mode"\n raise SyntaxError(msg) from e\n\n logger.debug("- raw mode: %s", rawmode)\n logger.debug("- pil mode: %s", self.mode)\n\n self.info["compression"] = self._compression\n\n xres = self.tag_v2.get(X_RESOLUTION, 1)\n yres = self.tag_v2.get(Y_RESOLUTION, 1)\n\n if xres and yres:\n resunit = self.tag_v2.get(RESOLUTION_UNIT)\n if resunit == 2: # dots per inch\n self.info["dpi"] = (xres, yres)\n elif resunit == 3: # dots per centimeter. convert to dpi\n self.info["dpi"] = (xres * 2.54, yres * 2.54)\n elif resunit is None: # used to default to 1, but now 2)\n self.info["dpi"] = (xres, yres)\n # For backward compatibility,\n # we also preserve the old behavior\n self.info["resolution"] = xres, yres\n else: # No absolute unit of measurement\n self.info["resolution"] = xres, yres\n\n # build tile descriptors\n x = y = layer = 0\n self.tile = []\n self.use_load_libtiff = READ_LIBTIFF or self._compression != "raw"\n if self.use_load_libtiff:\n # Decoder expects entire file as one tile.\n # There's a buffer size limit in load (64k)\n # so large g4 images will fail if we use that\n # function.\n #\n # Setup the one tile for the whole image, then\n # use the _load_libtiff function.\n\n # libtiff handles the fillmode for us, so 1;IR should\n # actually be 1;I. Including the R double reverses the\n # bits, so stripes of the image are reversed. See\n # https://github.com/python-pillow/Pillow/issues/279\n if fillorder == 2:\n # Replace fillorder with fillorder=1\n key = key[:3] + (1,) + key[4:]\n logger.debug("format key: %s", key)\n # this should always work, since all the\n # fillorder==2 modes have a corresponding\n # fillorder=1 mode\n self._mode, rawmode = OPEN_INFO[key]\n # YCbCr images with new jpeg compression with pixels in one plane\n # unpacked straight into RGB values\n if (\n photo == 6\n and self._compression == "jpeg"\n and self._planar_configuration == 1\n ):\n rawmode = "RGB"\n # libtiff always returns the bytes in native order.\n # we're expecting image byte order. So, if the rawmode\n # contains I;16, we need to convert from native to image\n # byte order.\n elif rawmode == "I;16":\n rawmode = "I;16N"\n elif rawmode.endswith((";16B", ";16L")):\n rawmode = rawmode[:-1] + "N"\n\n # Offset in the tile tuple is 0, we go from 0,0 to\n # w,h, and we only do this once -- eds\n a = (rawmode, self._compression, False, self.tag_v2.offset)\n self.tile.append(ImageFile._Tile("libtiff", (0, 0, xsize, ysize), 0, a))\n\n elif STRIPOFFSETS in self.tag_v2 or TILEOFFSETS in self.tag_v2:\n # striped image\n if STRIPOFFSETS in self.tag_v2:\n offsets = self.tag_v2[STRIPOFFSETS]\n h = self.tag_v2.get(ROWSPERSTRIP, ysize)\n w = xsize\n else:\n # tiled image\n offsets = self.tag_v2[TILEOFFSETS]\n tilewidth = self.tag_v2.get(TILEWIDTH)\n h = self.tag_v2.get(TILELENGTH)\n if not isinstance(tilewidth, int) or not isinstance(h, int):\n msg = "Invalid tile dimensions"\n raise ValueError(msg)\n w = tilewidth\n\n if w == xsize and h == ysize and self._planar_configuration != 2:\n # Every tile covers the image. Only use the last offset\n offsets = offsets[-1:]\n\n for offset in offsets:\n if x + w > xsize:\n stride = w * sum(bps_tuple) / 8 # bytes per line\n else:\n stride = 0\n\n tile_rawmode = rawmode\n if self._planar_configuration == 2:\n # each band on it's own layer\n tile_rawmode = rawmode[layer]\n # adjust stride width accordingly\n stride /= bps_count\n\n args = (tile_rawmode, int(stride), 1)\n self.tile.append(\n ImageFile._Tile(\n self._compression,\n (x, y, min(x + w, xsize), min(y + h, ysize)),\n offset,\n args,\n )\n )\n x += w\n if x >= xsize:\n x, y = 0, y + h\n if y >= ysize:\n y = 0\n layer += 1\n else:\n logger.debug("- unsupported data organization")\n msg = "unknown data organization"\n raise SyntaxError(msg)\n\n # Fix up info.\n if ICCPROFILE in self.tag_v2:\n self.info["icc_profile"] = self.tag_v2[ICCPROFILE]\n\n # fixup palette descriptor\n\n if self.mode in ["P", "PA"]:\n palette = [o8(b // 256) for b in self.tag_v2[COLORMAP]]\n self.palette = ImagePalette.raw("RGB;L", b"".join(palette))\n\n\n#\n# --------------------------------------------------------------------\n# Write TIFF files\n\n# little endian is default except for image modes with\n# explicit big endian byte-order\n\nSAVE_INFO = {\n # mode => rawmode, byteorder, photometrics,\n # sampleformat, bitspersample, extra\n "1": ("1", II, 1, 1, (1,), None),\n "L": ("L", II, 1, 1, (8,), None),\n "LA": ("LA", II, 1, 1, (8, 8), 2),\n "P": ("P", II, 3, 1, (8,), None),\n "PA": ("PA", II, 3, 1, (8, 8), 2),\n "I": ("I;32S", II, 1, 2, (32,), None),\n "I;16": ("I;16", II, 1, 1, (16,), None),\n "I;16L": ("I;16L", II, 1, 1, (16,), None),\n "F": ("F;32F", II, 1, 3, (32,), None),\n "RGB": ("RGB", II, 2, 1, (8, 8, 8), None),\n "RGBX": ("RGBX", II, 2, 1, (8, 8, 8, 8), 0),\n "RGBA": ("RGBA", II, 2, 1, (8, 8, 8, 8), 2),\n "CMYK": ("CMYK", II, 5, 1, (8, 8, 8, 8), None),\n "YCbCr": ("YCbCr", II, 6, 1, (8, 8, 8), None),\n "LAB": ("LAB", II, 8, 1, (8, 8, 8), None),\n "I;16B": ("I;16B", MM, 1, 1, (16,), None),\n}\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n try:\n rawmode, prefix, photo, format, bits, extra = SAVE_INFO[im.mode]\n except KeyError as e:\n msg = f"cannot write mode {im.mode} as TIFF"\n raise OSError(msg) from e\n\n encoderinfo = im.encoderinfo\n encoderconfig = im.encoderconfig\n\n ifd = ImageFileDirectory_v2(prefix=prefix)\n if encoderinfo.get("big_tiff"):\n ifd._bigtiff = True\n\n try:\n compression = encoderinfo["compression"]\n except KeyError:\n compression = im.info.get("compression")\n if isinstance(compression, int):\n # compression value may be from BMP. Ignore it\n compression = None\n if compression is None:\n compression = "raw"\n elif compression == "tiff_jpeg":\n # OJPEG is obsolete, so use new-style JPEG compression instead\n compression = "jpeg"\n elif compression == "tiff_deflate":\n compression = "tiff_adobe_deflate"\n\n libtiff = WRITE_LIBTIFF or compression != "raw"\n\n # required for color libtiff images\n ifd[PLANAR_CONFIGURATION] = 1\n\n ifd[IMAGEWIDTH] = im.size[0]\n ifd[IMAGELENGTH] = im.size[1]\n\n # write any arbitrary tags passed in as an ImageFileDirectory\n if "tiffinfo" in encoderinfo:\n info = encoderinfo["tiffinfo"]\n elif "exif" in encoderinfo:\n info = encoderinfo["exif"]\n if isinstance(info, bytes):\n exif = Image.Exif()\n exif.load(info)\n info = exif\n else:\n info = {}\n logger.debug("Tiffinfo Keys: %s", list(info))\n if isinstance(info, ImageFileDirectory_v1):\n info = info.to_v2()\n for key in info:\n if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:\n ifd[key] = info.get_ifd(key)\n else:\n ifd[key] = info.get(key)\n try:\n ifd.tagtype[key] = info.tagtype[key]\n except Exception:\n pass # might not be an IFD. Might not have populated type\n\n legacy_ifd = {}\n if hasattr(im, "tag"):\n legacy_ifd = im.tag.to_v2()\n\n supplied_tags = {**legacy_ifd, **getattr(im, "tag_v2", {})}\n for tag in (\n # IFD offset that may not be correct in the saved image\n EXIFIFD,\n # Determined by the image format and should not be copied from legacy_ifd.\n SAMPLEFORMAT,\n ):\n if tag in supplied_tags:\n del supplied_tags[tag]\n\n # additions written by Greg Couch, gregc@cgl.ucsf.edu\n # inspired by image-sig posting from Kevin Cazabon, kcazabon@home.com\n if hasattr(im, "tag_v2"):\n # preserve tags from original TIFF image file\n for key in (\n RESOLUTION_UNIT,\n X_RESOLUTION,\n Y_RESOLUTION,\n IPTC_NAA_CHUNK,\n PHOTOSHOP_CHUNK,\n XMP,\n ):\n if key in im.tag_v2:\n if key == IPTC_NAA_CHUNK and im.tag_v2.tagtype[key] not in (\n TiffTags.BYTE,\n TiffTags.UNDEFINED,\n ):\n del supplied_tags[key]\n else:\n ifd[key] = im.tag_v2[key]\n ifd.tagtype[key] = im.tag_v2.tagtype[key]\n\n # preserve ICC profile (should also work when saving other formats\n # which support profiles as TIFF) -- 2008-06-06 Florian Hoech\n icc = encoderinfo.get("icc_profile", im.info.get("icc_profile"))\n if icc:\n ifd[ICCPROFILE] = icc\n\n for key, name in [\n (IMAGEDESCRIPTION, "description"),\n (X_RESOLUTION, "resolution"),\n (Y_RESOLUTION, "resolution"),\n (X_RESOLUTION, "x_resolution"),\n (Y_RESOLUTION, "y_resolution"),\n (RESOLUTION_UNIT, "resolution_unit"),\n (SOFTWARE, "software"),\n (DATE_TIME, "date_time"),\n (ARTIST, "artist"),\n (COPYRIGHT, "copyright"),\n ]:\n if name in encoderinfo:\n ifd[key] = encoderinfo[name]\n\n dpi = encoderinfo.get("dpi")\n if dpi:\n ifd[RESOLUTION_UNIT] = 2\n ifd[X_RESOLUTION] = dpi[0]\n ifd[Y_RESOLUTION] = dpi[1]\n\n if bits != (1,):\n ifd[BITSPERSAMPLE] = bits\n if len(bits) != 1:\n ifd[SAMPLESPERPIXEL] = len(bits)\n if extra is not None:\n ifd[EXTRASAMPLES] = extra\n if format != 1:\n ifd[SAMPLEFORMAT] = format\n\n if PHOTOMETRIC_INTERPRETATION not in ifd:\n ifd[PHOTOMETRIC_INTERPRETATION] = photo\n elif im.mode in ("1", "L") and ifd[PHOTOMETRIC_INTERPRETATION] == 0:\n if im.mode == "1":\n inverted_im = im.copy()\n px = inverted_im.load()\n if px is not None:\n for y in range(inverted_im.height):\n for x in range(inverted_im.width):\n px[x, y] = 0 if px[x, y] == 255 else 255\n im = inverted_im\n else:\n im = ImageOps.invert(im)\n\n if im.mode in ["P", "PA"]:\n lut = im.im.getpalette("RGB", "RGB;L")\n colormap = []\n colors = len(lut) // 3\n for i in range(3):\n colormap += [v * 256 for v in lut[colors * i : colors * (i + 1)]]\n colormap += [0] * (256 - colors)\n ifd[COLORMAP] = colormap\n # data orientation\n w, h = ifd[IMAGEWIDTH], ifd[IMAGELENGTH]\n stride = len(bits) * ((w * bits[0] + 7) // 8)\n if ROWSPERSTRIP not in ifd:\n # aim for given strip size (64 KB by default) when using libtiff writer\n if libtiff:\n im_strip_size = encoderinfo.get("strip_size", STRIP_SIZE)\n rows_per_strip = 1 if stride == 0 else min(im_strip_size // stride, h)\n # JPEG encoder expects multiple of 8 rows\n if compression == "jpeg":\n rows_per_strip = min(((rows_per_strip + 7) // 8) * 8, h)\n else:\n rows_per_strip = h\n if rows_per_strip == 0:\n rows_per_strip = 1\n ifd[ROWSPERSTRIP] = rows_per_strip\n strip_byte_counts = 1 if stride == 0 else stride * ifd[ROWSPERSTRIP]\n strips_per_image = (h + ifd[ROWSPERSTRIP] - 1) // ifd[ROWSPERSTRIP]\n if strip_byte_counts >= 2**16:\n ifd.tagtype[STRIPBYTECOUNTS] = TiffTags.LONG\n ifd[STRIPBYTECOUNTS] = (strip_byte_counts,) * (strips_per_image - 1) + (\n stride * h - strip_byte_counts * (strips_per_image - 1),\n )\n ifd[STRIPOFFSETS] = tuple(\n range(0, strip_byte_counts * strips_per_image, strip_byte_counts)\n ) # this is adjusted by IFD writer\n # no compression by default:\n ifd[COMPRESSION] = COMPRESSION_INFO_REV.get(compression, 1)\n\n if im.mode == "YCbCr":\n for tag, default_value in {\n YCBCRSUBSAMPLING: (1, 1),\n REFERENCEBLACKWHITE: (0, 255, 128, 255, 128, 255),\n }.items():\n ifd.setdefault(tag, default_value)\n\n blocklist = [TILEWIDTH, TILELENGTH, TILEOFFSETS, TILEBYTECOUNTS]\n if libtiff:\n if "quality" in encoderinfo:\n quality = encoderinfo["quality"]\n if not isinstance(quality, int) or quality < 0 or quality > 100:\n msg = "Invalid quality setting"\n raise ValueError(msg)\n if compression != "jpeg":\n msg = "quality setting only supported for 'jpeg' compression"\n raise ValueError(msg)\n ifd[JPEGQUALITY] = quality\n\n logger.debug("Saving using libtiff encoder")\n logger.debug("Items: %s", sorted(ifd.items()))\n _fp = 0\n if hasattr(fp, "fileno"):\n try:\n fp.seek(0)\n _fp = fp.fileno()\n except io.UnsupportedOperation:\n pass\n\n # optional types for non core tags\n types = {}\n # STRIPOFFSETS and STRIPBYTECOUNTS are added by the library\n # based on the data in the strip.\n # OSUBFILETYPE is deprecated.\n # The other tags expect arrays with a certain length (fixed or depending on\n # BITSPERSAMPLE, etc), passing arrays with a different length will result in\n # segfaults. Block these tags until we add extra validation.\n # SUBIFD may also cause a segfault.\n blocklist += [\n OSUBFILETYPE,\n REFERENCEBLACKWHITE,\n STRIPBYTECOUNTS,\n STRIPOFFSETS,\n TRANSFERFUNCTION,\n SUBIFD,\n ]\n\n # bits per sample is a single short in the tiff directory, not a list.\n atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]}\n # Merge the ones that we have with (optional) more bits from\n # the original file, e.g x,y resolution so that we can\n # save(load('')) == original file.\n for tag, value in itertools.chain(ifd.items(), supplied_tags.items()):\n # Libtiff can only process certain core items without adding\n # them to the custom dictionary.\n # Custom items are supported for int, float, unicode, string and byte\n # values. Other types and tuples require a tagtype.\n if tag not in TiffTags.LIBTIFF_CORE:\n if not getattr(Image.core, "libtiff_support_custom_tags", False):\n continue\n\n if tag in TiffTags.TAGS_V2_GROUPS:\n types[tag] = TiffTags.LONG8\n elif tag in ifd.tagtype:\n types[tag] = ifd.tagtype[tag]\n elif not (isinstance(value, (int, float, str, bytes))):\n continue\n else:\n type = TiffTags.lookup(tag).type\n if type:\n types[tag] = type\n if tag not in atts and tag not in blocklist:\n if isinstance(value, str):\n atts[tag] = value.encode("ascii", "replace") + b"\0"\n elif isinstance(value, IFDRational):\n atts[tag] = float(value)\n else:\n atts[tag] = value\n\n if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1:\n atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0]\n\n logger.debug("Converted items: %s", sorted(atts.items()))\n\n # libtiff always expects the bytes in native order.\n # we're storing image byte order. So, if the rawmode\n # contains I;16, we need to convert from native to image\n # byte order.\n if im.mode in ("I;16", "I;16B", "I;16L"):\n rawmode = "I;16N"\n\n # Pass tags as sorted list so that the tags are set in a fixed order.\n # This is required by libtiff for some tags. For example, the JPEGQUALITY\n # pseudo tag requires that the COMPRESS tag was already set.\n tags = list(atts.items())\n tags.sort()\n a = (rawmode, compression, _fp, filename, tags, types)\n encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)\n encoder.setimage(im.im, (0, 0) + im.size)\n while True:\n errcode, data = encoder.encode(ImageFile.MAXBLOCK)[1:]\n if not _fp:\n fp.write(data)\n if errcode:\n break\n if errcode < 0:\n msg = f"encoder error {errcode} when writing image file"\n raise OSError(msg)\n\n else:\n for tag in blocklist:\n del ifd[tag]\n offset = ifd.save(fp)\n\n ImageFile._save(\n im,\n fp,\n [ImageFile._Tile("raw", (0, 0) + im.size, offset, (rawmode, stride, 1))],\n )\n\n # -- helper for multi-page save --\n if "_debug_multipage" in encoderinfo:\n # just to access o32 and o16 (using correct byte order)\n setattr(im, "_debug_multipage", ifd)\n\n\nclass AppendingTiffWriter(io.BytesIO):\n fieldSizes = [\n 0, # None\n 1, # byte\n 1, # ascii\n 2, # short\n 4, # long\n 8, # rational\n 1, # sbyte\n 1, # undefined\n 2, # sshort\n 4, # slong\n 8, # srational\n 4, # float\n 8, # double\n 4, # ifd\n 2, # unicode\n 4, # complex\n 8, # long8\n ]\n\n Tags = {\n 273, # StripOffsets\n 288, # FreeOffsets\n 324, # TileOffsets\n 519, # JPEGQTables\n 520, # JPEGDCTables\n 521, # JPEGACTables\n }\n\n def __init__(self, fn: StrOrBytesPath | IO[bytes], new: bool = False) -> None:\n self.f: IO[bytes]\n if is_path(fn):\n self.name = fn\n self.close_fp = True\n try:\n self.f = open(fn, "w+b" if new else "r+b")\n except OSError:\n self.f = open(fn, "w+b")\n else:\n self.f = cast(IO[bytes], fn)\n self.close_fp = False\n self.beginning = self.f.tell()\n self.setup()\n\n def setup(self) -> None:\n # Reset everything.\n self.f.seek(self.beginning, os.SEEK_SET)\n\n self.whereToWriteNewIFDOffset: int | None = None\n self.offsetOfNewPage = 0\n\n self.IIMM = iimm = self.f.read(4)\n self._bigtiff = b"\x2b" in iimm\n if not iimm:\n # empty file - first page\n self.isFirst = True\n return\n\n self.isFirst = False\n if iimm not in PREFIXES:\n msg = "Invalid TIFF file header"\n raise RuntimeError(msg)\n\n self.setEndian("<" if iimm.startswith(II) else ">")\n\n if self._bigtiff:\n self.f.seek(4, os.SEEK_CUR)\n self.skipIFDs()\n self.goToEnd()\n\n def finalize(self) -> None:\n if self.isFirst:\n return\n\n # fix offsets\n self.f.seek(self.offsetOfNewPage)\n\n iimm = self.f.read(4)\n if not iimm:\n # Make it easy to finish a frame without committing to a new one.\n return\n\n if iimm != self.IIMM:\n msg = "IIMM of new page doesn't match IIMM of first page"\n raise RuntimeError(msg)\n\n if self._bigtiff:\n self.f.seek(4, os.SEEK_CUR)\n ifd_offset = self._read(8 if self._bigtiff else 4)\n ifd_offset += self.offsetOfNewPage\n assert self.whereToWriteNewIFDOffset is not None\n self.f.seek(self.whereToWriteNewIFDOffset)\n self._write(ifd_offset, 8 if self._bigtiff else 4)\n self.f.seek(ifd_offset)\n self.fixIFD()\n\n def newFrame(self) -> None:\n # Call this to finish a frame.\n self.finalize()\n self.setup()\n\n def __enter__(self) -> AppendingTiffWriter:\n return self\n\n def __exit__(self, *args: object) -> None:\n if self.close_fp:\n self.close()\n\n def tell(self) -> int:\n return self.f.tell() - self.offsetOfNewPage\n\n def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:\n """\n :param offset: Distance to seek.\n :param whence: Whether the distance is relative to the start,\n end or current position.\n :returns: The resulting position, relative to the start.\n """\n if whence == os.SEEK_SET:\n offset += self.offsetOfNewPage\n\n self.f.seek(offset, whence)\n return self.tell()\n\n def goToEnd(self) -> None:\n self.f.seek(0, os.SEEK_END)\n pos = self.f.tell()\n\n # pad to 16 byte boundary\n pad_bytes = 16 - pos % 16\n if 0 < pad_bytes < 16:\n self.f.write(bytes(pad_bytes))\n self.offsetOfNewPage = self.f.tell()\n\n def setEndian(self, endian: str) -> None:\n self.endian = endian\n self.longFmt = f"{self.endian}L"\n self.shortFmt = f"{self.endian}H"\n self.tagFormat = f"{self.endian}HH" + ("Q" if self._bigtiff else "L")\n\n def skipIFDs(self) -> None:\n while True:\n ifd_offset = self._read(8 if self._bigtiff else 4)\n if ifd_offset == 0:\n self.whereToWriteNewIFDOffset = self.f.tell() - (\n 8 if self._bigtiff else 4\n )\n break\n\n self.f.seek(ifd_offset)\n num_tags = self._read(8 if self._bigtiff else 2)\n self.f.seek(num_tags * (20 if self._bigtiff else 12), os.SEEK_CUR)\n\n def write(self, data: Buffer, /) -> int:\n return self.f.write(data)\n\n def _fmt(self, field_size: int) -> str:\n try:\n return {2: "H", 4: "L", 8: "Q"}[field_size]\n except KeyError:\n msg = "offset is not supported"\n raise RuntimeError(msg)\n\n def _read(self, field_size: int) -> int:\n (value,) = struct.unpack(\n self.endian + self._fmt(field_size), self.f.read(field_size)\n )\n return value\n\n def readShort(self) -> int:\n return self._read(2)\n\n def readLong(self) -> int:\n return self._read(4)\n\n @staticmethod\n def _verify_bytes_written(bytes_written: int | None, expected: int) -> None:\n if bytes_written is not None and bytes_written != expected:\n msg = f"wrote only {bytes_written} bytes but wanted {expected}"\n raise RuntimeError(msg)\n\n def _rewriteLast(\n self, value: int, field_size: int, new_field_size: int = 0\n ) -> None:\n self.f.seek(-field_size, os.SEEK_CUR)\n if not new_field_size:\n new_field_size = field_size\n bytes_written = self.f.write(\n struct.pack(self.endian + self._fmt(new_field_size), value)\n )\n self._verify_bytes_written(bytes_written, new_field_size)\n\n def rewriteLastShortToLong(self, value: int) -> None:\n self._rewriteLast(value, 2, 4)\n\n def rewriteLastShort(self, value: int) -> None:\n return self._rewriteLast(value, 2)\n\n def rewriteLastLong(self, value: int) -> None:\n return self._rewriteLast(value, 4)\n\n def _write(self, value: int, field_size: int) -> None:\n bytes_written = self.f.write(\n struct.pack(self.endian + self._fmt(field_size), value)\n )\n self._verify_bytes_written(bytes_written, field_size)\n\n def writeShort(self, value: int) -> None:\n self._write(value, 2)\n\n def writeLong(self, value: int) -> None:\n self._write(value, 4)\n\n def close(self) -> None:\n self.finalize()\n if self.close_fp:\n self.f.close()\n\n def fixIFD(self) -> None:\n num_tags = self._read(8 if self._bigtiff else 2)\n\n for i in range(num_tags):\n tag, field_type, count = struct.unpack(\n self.tagFormat, self.f.read(12 if self._bigtiff else 8)\n )\n\n field_size = self.fieldSizes[field_type]\n total_size = field_size * count\n fmt_size = 8 if self._bigtiff else 4\n is_local = total_size <= fmt_size\n if not is_local:\n offset = self._read(fmt_size) + self.offsetOfNewPage\n self._rewriteLast(offset, fmt_size)\n\n if tag in self.Tags:\n cur_pos = self.f.tell()\n\n logger.debug(\n "fixIFD: %s (%d) - type: %s (%d) - type size: %d - count: %d",\n TiffTags.lookup(tag).name,\n tag,\n TYPES.get(field_type, "unknown"),\n field_type,\n field_size,\n count,\n )\n\n if is_local:\n self._fixOffsets(count, field_size)\n self.f.seek(cur_pos + fmt_size)\n else:\n self.f.seek(offset)\n self._fixOffsets(count, field_size)\n self.f.seek(cur_pos)\n\n elif is_local:\n # skip the locally stored value that is not an offset\n self.f.seek(fmt_size, os.SEEK_CUR)\n\n def _fixOffsets(self, count: int, field_size: int) -> None:\n for i in range(count):\n offset = self._read(field_size)\n offset += self.offsetOfNewPage\n\n new_field_size = 0\n if self._bigtiff and field_size in (2, 4) and offset >= 2**32:\n # offset is now too large - we must convert long to long8\n new_field_size = 8\n elif field_size == 2 and offset >= 2**16:\n # offset is now too large - we must convert short to long\n new_field_size = 4\n if new_field_size:\n if count != 1:\n msg = "not implemented"\n raise RuntimeError(msg) # XXX TODO\n\n # simple case - the offset is just one and therefore it is\n # local (not referenced with another offset)\n self._rewriteLast(offset, field_size, new_field_size)\n # Move back past the new offset, past 'count', and before 'field_type'\n rewind = -new_field_size - 4 - 2\n self.f.seek(rewind, os.SEEK_CUR)\n self.writeShort(new_field_size) # rewrite the type\n self.f.seek(2 - rewind, os.SEEK_CUR)\n else:\n self._rewriteLast(offset, field_size)\n\n def fixOffsets(\n self, count: int, isShort: bool = False, isLong: bool = False\n ) -> None:\n if isShort:\n field_size = 2\n elif isLong:\n field_size = 4\n else:\n field_size = 0\n return self._fixOffsets(count, field_size)\n\n\ndef _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n append_images = list(im.encoderinfo.get("append_images", []))\n if not hasattr(im, "n_frames") and not append_images:\n return _save(im, fp, filename)\n\n cur_idx = im.tell()\n try:\n with AppendingTiffWriter(fp) as tf:\n for ims in [im] + append_images:\n encoderinfo = ims._attach_default_encoderinfo(im)\n if not hasattr(ims, "encoderconfig"):\n ims.encoderconfig = ()\n nfr = getattr(ims, "n_frames", 1)\n\n for idx in range(nfr):\n ims.seek(idx)\n ims.load()\n _save(ims, tf, filename)\n tf.newFrame()\n ims.encoderinfo = encoderinfo\n finally:\n im.seek(cur_idx)\n\n\n#\n# --------------------------------------------------------------------\n# Register\n\nImage.register_open(TiffImageFile.format, TiffImageFile, _accept)\nImage.register_save(TiffImageFile.format, _save)\nImage.register_save_all(TiffImageFile.format, _save_all)\n\nImage.register_extensions(TiffImageFile.format, [".tif", ".tiff"])\n\nImage.register_mime(TiffImageFile.format, "image/tiff")\n | .venv\Lib\site-packages\PIL\TiffImagePlugin.py | TiffImagePlugin.py | Python | 87,368 | 0.75 | 0.194955 | 0.120542 | awesome-app | 177 | 2024-01-26T17:27:27.428015 | MIT | false | 33723937266dfad6cc41dfb356bf914b |
#\n# The Python Imaging Library.\n# $Id$\n#\n# TIFF tags\n#\n# This module provides clear-text names for various well-known\n# TIFF tags. the TIFF codec works just fine without it.\n#\n# Copyright (c) Secret Labs AB 1999.\n#\n# See the README file for information on usage and redistribution.\n#\n\n##\n# This module provides constants and clear-text names for various\n# well-known TIFF tags.\n##\nfrom __future__ import annotations\n\nfrom typing import NamedTuple\n\n\nclass _TagInfo(NamedTuple):\n value: int | None\n name: str\n type: int | None\n length: int | None\n enum: dict[str, int]\n\n\nclass TagInfo(_TagInfo):\n __slots__: list[str] = []\n\n def __new__(\n cls,\n value: int | None = None,\n name: str = "unknown",\n type: int | None = None,\n length: int | None = None,\n enum: dict[str, int] | None = None,\n ) -> TagInfo:\n return super().__new__(cls, value, name, type, length, enum or {})\n\n def cvt_enum(self, value: str) -> int | str:\n # Using get will call hash(value), which can be expensive\n # for some types (e.g. Fraction). Since self.enum is rarely\n # used, it's usually better to test it first.\n return self.enum.get(value, value) if self.enum else value\n\n\ndef lookup(tag: int, group: int | None = None) -> TagInfo:\n """\n :param tag: Integer tag number\n :param group: Which :py:data:`~PIL.TiffTags.TAGS_V2_GROUPS` to look in\n\n .. versionadded:: 8.3.0\n\n :returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible,\n otherwise just populating the value and name from ``TAGS``.\n If the tag is not recognized, "unknown" is returned for the name\n\n """\n\n if group is not None:\n info = TAGS_V2_GROUPS[group].get(tag) if group in TAGS_V2_GROUPS else None\n else:\n info = TAGS_V2.get(tag)\n return info or TagInfo(tag, TAGS.get(tag, "unknown"))\n\n\n##\n# Map tag numbers to tag info.\n#\n# id: (Name, Type, Length[, enum_values])\n#\n# The length here differs from the length in the tiff spec. For\n# numbers, the tiff spec is for the number of fields returned. We\n# agree here. For string-like types, the tiff spec uses the length of\n# field in bytes. In Pillow, we are using the number of expected\n# fields, in general 1 for string-like types.\n\n\nBYTE = 1\nASCII = 2\nSHORT = 3\nLONG = 4\nRATIONAL = 5\nSIGNED_BYTE = 6\nUNDEFINED = 7\nSIGNED_SHORT = 8\nSIGNED_LONG = 9\nSIGNED_RATIONAL = 10\nFLOAT = 11\nDOUBLE = 12\nIFD = 13\nLONG8 = 16\n\n_tags_v2: dict[int, tuple[str, int, int] | tuple[str, int, int, dict[str, int]]] = {\n 254: ("NewSubfileType", LONG, 1),\n 255: ("SubfileType", SHORT, 1),\n 256: ("ImageWidth", LONG, 1),\n 257: ("ImageLength", LONG, 1),\n 258: ("BitsPerSample", SHORT, 0),\n 259: (\n "Compression",\n SHORT,\n 1,\n {\n "Uncompressed": 1,\n "CCITT 1d": 2,\n "Group 3 Fax": 3,\n "Group 4 Fax": 4,\n "LZW": 5,\n "JPEG": 6,\n "PackBits": 32773,\n },\n ),\n 262: (\n "PhotometricInterpretation",\n SHORT,\n 1,\n {\n "WhiteIsZero": 0,\n "BlackIsZero": 1,\n "RGB": 2,\n "RGB Palette": 3,\n "Transparency Mask": 4,\n "CMYK": 5,\n "YCbCr": 6,\n "CieLAB": 8,\n "CFA": 32803, # TIFF/EP, Adobe DNG\n "LinearRaw": 32892, # Adobe DNG\n },\n ),\n 263: ("Threshholding", SHORT, 1),\n 264: ("CellWidth", SHORT, 1),\n 265: ("CellLength", SHORT, 1),\n 266: ("FillOrder", SHORT, 1),\n 269: ("DocumentName", ASCII, 1),\n 270: ("ImageDescription", ASCII, 1),\n 271: ("Make", ASCII, 1),\n 272: ("Model", ASCII, 1),\n 273: ("StripOffsets", LONG, 0),\n 274: ("Orientation", SHORT, 1),\n 277: ("SamplesPerPixel", SHORT, 1),\n 278: ("RowsPerStrip", LONG, 1),\n 279: ("StripByteCounts", LONG, 0),\n 280: ("MinSampleValue", SHORT, 0),\n 281: ("MaxSampleValue", SHORT, 0),\n 282: ("XResolution", RATIONAL, 1),\n 283: ("YResolution", RATIONAL, 1),\n 284: ("PlanarConfiguration", SHORT, 1, {"Contiguous": 1, "Separate": 2}),\n 285: ("PageName", ASCII, 1),\n 286: ("XPosition", RATIONAL, 1),\n 287: ("YPosition", RATIONAL, 1),\n 288: ("FreeOffsets", LONG, 1),\n 289: ("FreeByteCounts", LONG, 1),\n 290: ("GrayResponseUnit", SHORT, 1),\n 291: ("GrayResponseCurve", SHORT, 0),\n 292: ("T4Options", LONG, 1),\n 293: ("T6Options", LONG, 1),\n 296: ("ResolutionUnit", SHORT, 1, {"none": 1, "inch": 2, "cm": 3}),\n 297: ("PageNumber", SHORT, 2),\n 301: ("TransferFunction", SHORT, 0),\n 305: ("Software", ASCII, 1),\n 306: ("DateTime", ASCII, 1),\n 315: ("Artist", ASCII, 1),\n 316: ("HostComputer", ASCII, 1),\n 317: ("Predictor", SHORT, 1, {"none": 1, "Horizontal Differencing": 2}),\n 318: ("WhitePoint", RATIONAL, 2),\n 319: ("PrimaryChromaticities", RATIONAL, 6),\n 320: ("ColorMap", SHORT, 0),\n 321: ("HalftoneHints", SHORT, 2),\n 322: ("TileWidth", LONG, 1),\n 323: ("TileLength", LONG, 1),\n 324: ("TileOffsets", LONG, 0),\n 325: ("TileByteCounts", LONG, 0),\n 330: ("SubIFDs", LONG, 0),\n 332: ("InkSet", SHORT, 1),\n 333: ("InkNames", ASCII, 1),\n 334: ("NumberOfInks", SHORT, 1),\n 336: ("DotRange", SHORT, 0),\n 337: ("TargetPrinter", ASCII, 1),\n 338: ("ExtraSamples", SHORT, 0),\n 339: ("SampleFormat", SHORT, 0),\n 340: ("SMinSampleValue", DOUBLE, 0),\n 341: ("SMaxSampleValue", DOUBLE, 0),\n 342: ("TransferRange", SHORT, 6),\n 347: ("JPEGTables", UNDEFINED, 1),\n # obsolete JPEG tags\n 512: ("JPEGProc", SHORT, 1),\n 513: ("JPEGInterchangeFormat", LONG, 1),\n 514: ("JPEGInterchangeFormatLength", LONG, 1),\n 515: ("JPEGRestartInterval", SHORT, 1),\n 517: ("JPEGLosslessPredictors", SHORT, 0),\n 518: ("JPEGPointTransforms", SHORT, 0),\n 519: ("JPEGQTables", LONG, 0),\n 520: ("JPEGDCTables", LONG, 0),\n 521: ("JPEGACTables", LONG, 0),\n 529: ("YCbCrCoefficients", RATIONAL, 3),\n 530: ("YCbCrSubSampling", SHORT, 2),\n 531: ("YCbCrPositioning", SHORT, 1),\n 532: ("ReferenceBlackWhite", RATIONAL, 6),\n 700: ("XMP", BYTE, 0),\n 33432: ("Copyright", ASCII, 1),\n 33723: ("IptcNaaInfo", UNDEFINED, 1),\n 34377: ("PhotoshopInfo", BYTE, 0),\n # FIXME add more tags here\n 34665: ("ExifIFD", LONG, 1),\n 34675: ("ICCProfile", UNDEFINED, 1),\n 34853: ("GPSInfoIFD", LONG, 1),\n 36864: ("ExifVersion", UNDEFINED, 1),\n 37724: ("ImageSourceData", UNDEFINED, 1),\n 40965: ("InteroperabilityIFD", LONG, 1),\n 41730: ("CFAPattern", UNDEFINED, 1),\n # MPInfo\n 45056: ("MPFVersion", UNDEFINED, 1),\n 45057: ("NumberOfImages", LONG, 1),\n 45058: ("MPEntry", UNDEFINED, 1),\n 45059: ("ImageUIDList", UNDEFINED, 0), # UNDONE, check\n 45060: ("TotalFrames", LONG, 1),\n 45313: ("MPIndividualNum", LONG, 1),\n 45569: ("PanOrientation", LONG, 1),\n 45570: ("PanOverlap_H", RATIONAL, 1),\n 45571: ("PanOverlap_V", RATIONAL, 1),\n 45572: ("BaseViewpointNum", LONG, 1),\n 45573: ("ConvergenceAngle", SIGNED_RATIONAL, 1),\n 45574: ("BaselineLength", RATIONAL, 1),\n 45575: ("VerticalDivergence", SIGNED_RATIONAL, 1),\n 45576: ("AxisDistance_X", SIGNED_RATIONAL, 1),\n 45577: ("AxisDistance_Y", SIGNED_RATIONAL, 1),\n 45578: ("AxisDistance_Z", SIGNED_RATIONAL, 1),\n 45579: ("YawAngle", SIGNED_RATIONAL, 1),\n 45580: ("PitchAngle", SIGNED_RATIONAL, 1),\n 45581: ("RollAngle", SIGNED_RATIONAL, 1),\n 40960: ("FlashPixVersion", UNDEFINED, 1),\n 50741: ("MakerNoteSafety", SHORT, 1, {"Unsafe": 0, "Safe": 1}),\n 50780: ("BestQualityScale", RATIONAL, 1),\n 50838: ("ImageJMetaDataByteCounts", LONG, 0), # Can be more than one\n 50839: ("ImageJMetaData", UNDEFINED, 1), # see Issue #2006\n}\n_tags_v2_groups = {\n # ExifIFD\n 34665: {\n 36864: ("ExifVersion", UNDEFINED, 1),\n 40960: ("FlashPixVersion", UNDEFINED, 1),\n 40965: ("InteroperabilityIFD", LONG, 1),\n 41730: ("CFAPattern", UNDEFINED, 1),\n },\n # GPSInfoIFD\n 34853: {\n 0: ("GPSVersionID", BYTE, 4),\n 1: ("GPSLatitudeRef", ASCII, 2),\n 2: ("GPSLatitude", RATIONAL, 3),\n 3: ("GPSLongitudeRef", ASCII, 2),\n 4: ("GPSLongitude", RATIONAL, 3),\n 5: ("GPSAltitudeRef", BYTE, 1),\n 6: ("GPSAltitude", RATIONAL, 1),\n 7: ("GPSTimeStamp", RATIONAL, 3),\n 8: ("GPSSatellites", ASCII, 0),\n 9: ("GPSStatus", ASCII, 2),\n 10: ("GPSMeasureMode", ASCII, 2),\n 11: ("GPSDOP", RATIONAL, 1),\n 12: ("GPSSpeedRef", ASCII, 2),\n 13: ("GPSSpeed", RATIONAL, 1),\n 14: ("GPSTrackRef", ASCII, 2),\n 15: ("GPSTrack", RATIONAL, 1),\n 16: ("GPSImgDirectionRef", ASCII, 2),\n 17: ("GPSImgDirection", RATIONAL, 1),\n 18: ("GPSMapDatum", ASCII, 0),\n 19: ("GPSDestLatitudeRef", ASCII, 2),\n 20: ("GPSDestLatitude", RATIONAL, 3),\n 21: ("GPSDestLongitudeRef", ASCII, 2),\n 22: ("GPSDestLongitude", RATIONAL, 3),\n 23: ("GPSDestBearingRef", ASCII, 2),\n 24: ("GPSDestBearing", RATIONAL, 1),\n 25: ("GPSDestDistanceRef", ASCII, 2),\n 26: ("GPSDestDistance", RATIONAL, 1),\n 27: ("GPSProcessingMethod", UNDEFINED, 0),\n 28: ("GPSAreaInformation", UNDEFINED, 0),\n 29: ("GPSDateStamp", ASCII, 11),\n 30: ("GPSDifferential", SHORT, 1),\n },\n # InteroperabilityIFD\n 40965: {1: ("InteropIndex", ASCII, 1), 2: ("InteropVersion", UNDEFINED, 1)},\n}\n\n# Legacy Tags structure\n# these tags aren't included above, but were in the previous versions\nTAGS: dict[int | tuple[int, int], str] = {\n 347: "JPEGTables",\n 700: "XMP",\n # Additional Exif Info\n 32932: "Wang Annotation",\n 33434: "ExposureTime",\n 33437: "FNumber",\n 33445: "MD FileTag",\n 33446: "MD ScalePixel",\n 33447: "MD ColorTable",\n 33448: "MD LabName",\n 33449: "MD SampleInfo",\n 33450: "MD PrepDate",\n 33451: "MD PrepTime",\n 33452: "MD FileUnits",\n 33550: "ModelPixelScaleTag",\n 33723: "IptcNaaInfo",\n 33918: "INGR Packet Data Tag",\n 33919: "INGR Flag Registers",\n 33920: "IrasB Transformation Matrix",\n 33922: "ModelTiepointTag",\n 34264: "ModelTransformationTag",\n 34377: "PhotoshopInfo",\n 34735: "GeoKeyDirectoryTag",\n 34736: "GeoDoubleParamsTag",\n 34737: "GeoAsciiParamsTag",\n 34850: "ExposureProgram",\n 34852: "SpectralSensitivity",\n 34855: "ISOSpeedRatings",\n 34856: "OECF",\n 34864: "SensitivityType",\n 34865: "StandardOutputSensitivity",\n 34866: "RecommendedExposureIndex",\n 34867: "ISOSpeed",\n 34868: "ISOSpeedLatitudeyyy",\n 34869: "ISOSpeedLatitudezzz",\n 34908: "HylaFAX FaxRecvParams",\n 34909: "HylaFAX FaxSubAddress",\n 34910: "HylaFAX FaxRecvTime",\n 36864: "ExifVersion",\n 36867: "DateTimeOriginal",\n 36868: "DateTimeDigitized",\n 37121: "ComponentsConfiguration",\n 37122: "CompressedBitsPerPixel",\n 37724: "ImageSourceData",\n 37377: "ShutterSpeedValue",\n 37378: "ApertureValue",\n 37379: "BrightnessValue",\n 37380: "ExposureBiasValue",\n 37381: "MaxApertureValue",\n 37382: "SubjectDistance",\n 37383: "MeteringMode",\n 37384: "LightSource",\n 37385: "Flash",\n 37386: "FocalLength",\n 37396: "SubjectArea",\n 37500: "MakerNote",\n 37510: "UserComment",\n 37520: "SubSec",\n 37521: "SubSecTimeOriginal",\n 37522: "SubsecTimeDigitized",\n 40960: "FlashPixVersion",\n 40961: "ColorSpace",\n 40962: "PixelXDimension",\n 40963: "PixelYDimension",\n 40964: "RelatedSoundFile",\n 40965: "InteroperabilityIFD",\n 41483: "FlashEnergy",\n 41484: "SpatialFrequencyResponse",\n 41486: "FocalPlaneXResolution",\n 41487: "FocalPlaneYResolution",\n 41488: "FocalPlaneResolutionUnit",\n 41492: "SubjectLocation",\n 41493: "ExposureIndex",\n 41495: "SensingMethod",\n 41728: "FileSource",\n 41729: "SceneType",\n 41730: "CFAPattern",\n 41985: "CustomRendered",\n 41986: "ExposureMode",\n 41987: "WhiteBalance",\n 41988: "DigitalZoomRatio",\n 41989: "FocalLengthIn35mmFilm",\n 41990: "SceneCaptureType",\n 41991: "GainControl",\n 41992: "Contrast",\n 41993: "Saturation",\n 41994: "Sharpness",\n 41995: "DeviceSettingDescription",\n 41996: "SubjectDistanceRange",\n 42016: "ImageUniqueID",\n 42032: "CameraOwnerName",\n 42033: "BodySerialNumber",\n 42034: "LensSpecification",\n 42035: "LensMake",\n 42036: "LensModel",\n 42037: "LensSerialNumber",\n 42112: "GDAL_METADATA",\n 42113: "GDAL_NODATA",\n 42240: "Gamma",\n 50215: "Oce Scanjob Description",\n 50216: "Oce Application Selector",\n 50217: "Oce Identification Number",\n 50218: "Oce ImageLogic Characteristics",\n # Adobe DNG\n 50706: "DNGVersion",\n 50707: "DNGBackwardVersion",\n 50708: "UniqueCameraModel",\n 50709: "LocalizedCameraModel",\n 50710: "CFAPlaneColor",\n 50711: "CFALayout",\n 50712: "LinearizationTable",\n 50713: "BlackLevelRepeatDim",\n 50714: "BlackLevel",\n 50715: "BlackLevelDeltaH",\n 50716: "BlackLevelDeltaV",\n 50717: "WhiteLevel",\n 50718: "DefaultScale",\n 50719: "DefaultCropOrigin",\n 50720: "DefaultCropSize",\n 50721: "ColorMatrix1",\n 50722: "ColorMatrix2",\n 50723: "CameraCalibration1",\n 50724: "CameraCalibration2",\n 50725: "ReductionMatrix1",\n 50726: "ReductionMatrix2",\n 50727: "AnalogBalance",\n 50728: "AsShotNeutral",\n 50729: "AsShotWhiteXY",\n 50730: "BaselineExposure",\n 50731: "BaselineNoise",\n 50732: "BaselineSharpness",\n 50733: "BayerGreenSplit",\n 50734: "LinearResponseLimit",\n 50735: "CameraSerialNumber",\n 50736: "LensInfo",\n 50737: "ChromaBlurRadius",\n 50738: "AntiAliasStrength",\n 50740: "DNGPrivateData",\n 50778: "CalibrationIlluminant1",\n 50779: "CalibrationIlluminant2",\n 50784: "Alias Layer Metadata",\n}\n\nTAGS_V2: dict[int, TagInfo] = {}\nTAGS_V2_GROUPS: dict[int, dict[int, TagInfo]] = {}\n\n\ndef _populate() -> None:\n for k, v in _tags_v2.items():\n # Populate legacy structure.\n TAGS[k] = v[0]\n if len(v) == 4:\n for sk, sv in v[3].items():\n TAGS[(k, sv)] = sk\n\n TAGS_V2[k] = TagInfo(k, *v)\n\n for group, tags in _tags_v2_groups.items():\n TAGS_V2_GROUPS[group] = {k: TagInfo(k, *v) for k, v in tags.items()}\n\n\n_populate()\n##\n# Map type numbers to type names -- defined in ImageFileDirectory.\n\nTYPES: dict[int, str] = {}\n\n#\n# These tags are handled by default in libtiff, without\n# adding to the custom dictionary. From tif_dir.c, searching for\n# case TIFFTAG in the _TIFFVSetField function:\n# Line: item.\n# 148: case TIFFTAG_SUBFILETYPE:\n# 151: case TIFFTAG_IMAGEWIDTH:\n# 154: case TIFFTAG_IMAGELENGTH:\n# 157: case TIFFTAG_BITSPERSAMPLE:\n# 181: case TIFFTAG_COMPRESSION:\n# 202: case TIFFTAG_PHOTOMETRIC:\n# 205: case TIFFTAG_THRESHHOLDING:\n# 208: case TIFFTAG_FILLORDER:\n# 214: case TIFFTAG_ORIENTATION:\n# 221: case TIFFTAG_SAMPLESPERPIXEL:\n# 228: case TIFFTAG_ROWSPERSTRIP:\n# 238: case TIFFTAG_MINSAMPLEVALUE:\n# 241: case TIFFTAG_MAXSAMPLEVALUE:\n# 244: case TIFFTAG_SMINSAMPLEVALUE:\n# 247: case TIFFTAG_SMAXSAMPLEVALUE:\n# 250: case TIFFTAG_XRESOLUTION:\n# 256: case TIFFTAG_YRESOLUTION:\n# 262: case TIFFTAG_PLANARCONFIG:\n# 268: case TIFFTAG_XPOSITION:\n# 271: case TIFFTAG_YPOSITION:\n# 274: case TIFFTAG_RESOLUTIONUNIT:\n# 280: case TIFFTAG_PAGENUMBER:\n# 284: case TIFFTAG_HALFTONEHINTS:\n# 288: case TIFFTAG_COLORMAP:\n# 294: case TIFFTAG_EXTRASAMPLES:\n# 298: case TIFFTAG_MATTEING:\n# 305: case TIFFTAG_TILEWIDTH:\n# 316: case TIFFTAG_TILELENGTH:\n# 327: case TIFFTAG_TILEDEPTH:\n# 333: case TIFFTAG_DATATYPE:\n# 344: case TIFFTAG_SAMPLEFORMAT:\n# 361: case TIFFTAG_IMAGEDEPTH:\n# 364: case TIFFTAG_SUBIFD:\n# 376: case TIFFTAG_YCBCRPOSITIONING:\n# 379: case TIFFTAG_YCBCRSUBSAMPLING:\n# 383: case TIFFTAG_TRANSFERFUNCTION:\n# 389: case TIFFTAG_REFERENCEBLACKWHITE:\n# 393: case TIFFTAG_INKNAMES:\n\n# Following pseudo-tags are also handled by default in libtiff:\n# TIFFTAG_JPEGQUALITY 65537\n\n# some of these are not in our TAGS_V2 dict and were included from tiff.h\n\n# This list also exists in encode.c\nLIBTIFF_CORE = {\n 255,\n 256,\n 257,\n 258,\n 259,\n 262,\n 263,\n 266,\n 274,\n 277,\n 278,\n 280,\n 281,\n 340,\n 341,\n 282,\n 283,\n 284,\n 286,\n 287,\n 296,\n 297,\n 321,\n 320,\n 338,\n 32995,\n 322,\n 323,\n 32998,\n 32996,\n 339,\n 32997,\n 330,\n 531,\n 530,\n 301,\n 532,\n 333,\n # as above\n 269, # this has been in our tests forever, and works\n 65537,\n}\n\nLIBTIFF_CORE.remove(255) # We don't have support for subfiletypes\nLIBTIFF_CORE.remove(322) # We don't have support for writing tiled images with libtiff\nLIBTIFF_CORE.remove(323) # Tiled images\nLIBTIFF_CORE.remove(333) # Ink Names either\n\n# Note to advanced users: There may be combinations of these\n# parameters and values that when added properly, will work and\n# produce valid tiff images that may work in your application.\n# It is safe to add and remove tags from this set from Pillow's point\n# of view so long as you test against libtiff.\n | .venv\Lib\site-packages\PIL\TiffTags.py | TiffTags.py | Python | 17,644 | 0.95 | 0.046263 | 0.181818 | python-kit | 464 | 2025-03-06T17:38:45.201150 | MIT | false | 032769f85b52163e4269c2277a23cb3a |
#\n# The Python Imaging Library.\n# $Id$\n#\n# WAL file handling\n#\n# History:\n# 2003-04-23 fl created\n#\n# Copyright (c) 2003 by Fredrik Lundh.\n#\n# See the README file for information on usage and redistribution.\n#\n\n"""\nThis reader is based on the specification available from:\nhttps://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml\nand has been tested with a few sample files found using google.\n\n.. note::\n This format cannot be automatically recognized, so the reader\n is not registered for use with :py:func:`PIL.Image.open()`.\n To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.\n"""\nfrom __future__ import annotations\n\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i32le as i32\nfrom ._typing import StrOrBytesPath\n\n\nclass WalImageFile(ImageFile.ImageFile):\n format = "WAL"\n format_description = "Quake2 Texture"\n\n def _open(self) -> None:\n self._mode = "P"\n\n # read header fields\n header = self.fp.read(32 + 24 + 32 + 12)\n self._size = i32(header, 32), i32(header, 36)\n Image._decompression_bomb_check(self.size)\n\n # load pixel data\n offset = i32(header, 40)\n self.fp.seek(offset)\n\n # strings are null-terminated\n self.info["name"] = header[:32].split(b"\0", 1)[0]\n next_name = header[56 : 56 + 32].split(b"\0", 1)[0]\n if next_name:\n self.info["next_name"] = next_name\n\n def load(self) -> Image.core.PixelAccess | None:\n if self._im is None:\n self.im = Image.core.new(self.mode, self.size)\n self.frombytes(self.fp.read(self.size[0] * self.size[1]))\n self.putpalette(quake2palette)\n return Image.Image.load(self)\n\n\ndef open(filename: StrOrBytesPath | IO[bytes]) -> WalImageFile:\n """\n Load texture from a Quake2 WAL texture file.\n\n By default, a Quake2 standard palette is attached to the texture.\n To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.\n\n :param filename: WAL file name, or an opened file handle.\n :returns: An image instance.\n """\n return WalImageFile(filename)\n\n\nquake2palette = (\n # default palette taken from piffo 0.93 by Hans Häggström\n b"\x01\x01\x01\x0b\x0b\x0b\x12\x12\x12\x17\x17\x17\x1b\x1b\x1b\x1e"\n b"\x1e\x1e\x22\x22\x22\x26\x26\x26\x29\x29\x29\x2c\x2c\x2c\x2f\x2f"\n b"\x2f\x32\x32\x32\x35\x35\x35\x37\x37\x37\x3a\x3a\x3a\x3c\x3c\x3c"\n b"\x24\x1e\x13\x22\x1c\x12\x20\x1b\x12\x1f\x1a\x10\x1d\x19\x10\x1b"\n b"\x17\x0f\x1a\x16\x0f\x18\x14\x0d\x17\x13\x0d\x16\x12\x0d\x14\x10"\n b"\x0b\x13\x0f\x0b\x10\x0d\x0a\x0f\x0b\x0a\x0d\x0b\x07\x0b\x0a\x07"\n b"\x23\x23\x26\x22\x22\x25\x22\x20\x23\x21\x1f\x22\x20\x1e\x20\x1f"\n b"\x1d\x1e\x1d\x1b\x1c\x1b\x1a\x1a\x1a\x19\x19\x18\x17\x17\x17\x16"\n b"\x16\x14\x14\x14\x13\x13\x13\x10\x10\x10\x0f\x0f\x0f\x0d\x0d\x0d"\n b"\x2d\x28\x20\x29\x24\x1c\x27\x22\x1a\x25\x1f\x17\x38\x2e\x1e\x31"\n b"\x29\x1a\x2c\x25\x17\x26\x20\x14\x3c\x30\x14\x37\x2c\x13\x33\x28"\n b"\x12\x2d\x24\x10\x28\x1f\x0f\x22\x1a\x0b\x1b\x14\x0a\x13\x0f\x07"\n b"\x31\x1a\x16\x30\x17\x13\x2e\x16\x10\x2c\x14\x0d\x2a\x12\x0b\x27"\n b"\x0f\x0a\x25\x0f\x07\x21\x0d\x01\x1e\x0b\x01\x1c\x0b\x01\x1a\x0b"\n b"\x01\x18\x0a\x01\x16\x0a\x01\x13\x0a\x01\x10\x07\x01\x0d\x07\x01"\n b"\x29\x23\x1e\x27\x21\x1c\x26\x20\x1b\x25\x1f\x1a\x23\x1d\x19\x21"\n b"\x1c\x18\x20\x1b\x17\x1e\x19\x16\x1c\x18\x14\x1b\x17\x13\x19\x14"\n b"\x10\x17\x13\x0f\x14\x10\x0d\x12\x0f\x0b\x0f\x0b\x0a\x0b\x0a\x07"\n b"\x26\x1a\x0f\x23\x19\x0f\x20\x17\x0f\x1c\x16\x0f\x19\x13\x0d\x14"\n b"\x10\x0b\x10\x0d\x0a\x0b\x0a\x07\x33\x22\x1f\x35\x29\x26\x37\x2f"\n b"\x2d\x39\x35\x34\x37\x39\x3a\x33\x37\x39\x30\x34\x36\x2b\x31\x34"\n b"\x27\x2e\x31\x22\x2b\x2f\x1d\x28\x2c\x17\x25\x2a\x0f\x20\x26\x0d"\n b"\x1e\x25\x0b\x1c\x22\x0a\x1b\x20\x07\x19\x1e\x07\x17\x1b\x07\x14"\n b"\x18\x01\x12\x16\x01\x0f\x12\x01\x0b\x0d\x01\x07\x0a\x01\x01\x01"\n b"\x2c\x21\x21\x2a\x1f\x1f\x29\x1d\x1d\x27\x1c\x1c\x26\x1a\x1a\x24"\n b"\x18\x18\x22\x17\x17\x21\x16\x16\x1e\x13\x13\x1b\x12\x12\x18\x10"\n b"\x10\x16\x0d\x0d\x12\x0b\x0b\x0d\x0a\x0a\x0a\x07\x07\x01\x01\x01"\n b"\x2e\x30\x29\x2d\x2e\x27\x2b\x2c\x26\x2a\x2a\x24\x28\x29\x23\x27"\n b"\x27\x21\x26\x26\x1f\x24\x24\x1d\x22\x22\x1c\x1f\x1f\x1a\x1c\x1c"\n b"\x18\x19\x19\x16\x17\x17\x13\x13\x13\x10\x0f\x0f\x0d\x0b\x0b\x0a"\n b"\x30\x1e\x1b\x2d\x1c\x19\x2c\x1a\x17\x2a\x19\x14\x28\x17\x13\x26"\n b"\x16\x10\x24\x13\x0f\x21\x12\x0d\x1f\x10\x0b\x1c\x0f\x0a\x19\x0d"\n b"\x0a\x16\x0b\x07\x12\x0a\x07\x0f\x07\x01\x0a\x01\x01\x01\x01\x01"\n b"\x28\x29\x38\x26\x27\x36\x25\x26\x34\x24\x24\x31\x22\x22\x2f\x20"\n b"\x21\x2d\x1e\x1f\x2a\x1d\x1d\x27\x1b\x1b\x25\x19\x19\x21\x17\x17"\n b"\x1e\x14\x14\x1b\x13\x12\x17\x10\x0f\x13\x0d\x0b\x0f\x0a\x07\x07"\n b"\x2f\x32\x29\x2d\x30\x26\x2b\x2e\x24\x29\x2c\x21\x27\x2a\x1e\x25"\n b"\x28\x1c\x23\x26\x1a\x21\x25\x18\x1e\x22\x14\x1b\x1f\x10\x19\x1c"\n b"\x0d\x17\x1a\x0a\x13\x17\x07\x10\x13\x01\x0d\x0f\x01\x0a\x0b\x01"\n b"\x01\x3f\x01\x13\x3c\x0b\x1b\x39\x10\x20\x35\x14\x23\x31\x17\x23"\n b"\x2d\x18\x23\x29\x18\x3f\x3f\x3f\x3f\x3f\x39\x3f\x3f\x31\x3f\x3f"\n b"\x2a\x3f\x3f\x20\x3f\x3f\x14\x3f\x3c\x12\x3f\x39\x0f\x3f\x35\x0b"\n b"\x3f\x32\x07\x3f\x2d\x01\x3d\x2a\x01\x3b\x26\x01\x39\x21\x01\x37"\n b"\x1d\x01\x34\x1a\x01\x32\x16\x01\x2f\x12\x01\x2d\x0f\x01\x2a\x0b"\n b"\x01\x27\x07\x01\x23\x01\x01\x1d\x01\x01\x17\x01\x01\x10\x01\x01"\n b"\x3d\x01\x01\x19\x19\x3f\x3f\x01\x01\x01\x01\x3f\x16\x16\x13\x10"\n b"\x10\x0f\x0d\x0d\x0b\x3c\x2e\x2a\x36\x27\x20\x30\x21\x18\x29\x1b"\n b"\x10\x3c\x39\x37\x37\x32\x2f\x31\x2c\x28\x2b\x26\x21\x30\x22\x20"\n)\n | .venv\Lib\site-packages\PIL\WalImageFile.py | WalImageFile.py | Python | 5,831 | 0.95 | 0.070866 | 0.154545 | awesome-app | 586 | 2024-05-19T18:46:15.277079 | GPL-3.0 | false | dda62432542c9b0b1cbb6cac20ec0a21 |
from __future__ import annotations\n\nfrom io import BytesIO\nfrom typing import IO, Any\n\nfrom . import Image, ImageFile\n\ntry:\n from . import _webp\n\n SUPPORTED = True\nexcept ImportError:\n SUPPORTED = False\n\n\n_VP8_MODES_BY_IDENTIFIER = {\n b"VP8 ": "RGB",\n b"VP8X": "RGBA",\n b"VP8L": "RGBA", # lossless\n}\n\n\ndef _accept(prefix: bytes) -> bool | str:\n is_riff_file_format = prefix.startswith(b"RIFF")\n is_webp_file = prefix[8:12] == b"WEBP"\n is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER\n\n if is_riff_file_format and is_webp_file and is_valid_vp8_mode:\n if not SUPPORTED:\n return (\n "image file could not be identified because WEBP support not installed"\n )\n return True\n return False\n\n\nclass WebPImageFile(ImageFile.ImageFile):\n format = "WEBP"\n format_description = "WebP image"\n __loaded = 0\n __logical_frame = 0\n\n def _open(self) -> None:\n # Use the newer AnimDecoder API to parse the (possibly) animated file,\n # and access muxed chunks like ICC/EXIF/XMP.\n self._decoder = _webp.WebPAnimDecoder(self.fp.read())\n\n # Get info from decoder\n self._size, loop_count, bgcolor, frame_count, mode = self._decoder.get_info()\n self.info["loop"] = loop_count\n bg_a, bg_r, bg_g, bg_b = (\n (bgcolor >> 24) & 0xFF,\n (bgcolor >> 16) & 0xFF,\n (bgcolor >> 8) & 0xFF,\n bgcolor & 0xFF,\n )\n self.info["background"] = (bg_r, bg_g, bg_b, bg_a)\n self.n_frames = frame_count\n self.is_animated = self.n_frames > 1\n self._mode = "RGB" if mode == "RGBX" else mode\n self.rawmode = mode\n\n # Attempt to read ICC / EXIF / XMP chunks from file\n icc_profile = self._decoder.get_chunk("ICCP")\n exif = self._decoder.get_chunk("EXIF")\n xmp = self._decoder.get_chunk("XMP ")\n if icc_profile:\n self.info["icc_profile"] = icc_profile\n if exif:\n self.info["exif"] = exif\n if xmp:\n self.info["xmp"] = xmp\n\n # Initialize seek state\n self._reset(reset=False)\n\n def _getexif(self) -> dict[int, Any] | None:\n if "exif" not in self.info:\n return None\n return self.getexif()._get_merged_dict()\n\n def seek(self, frame: int) -> None:\n if not self._seek_check(frame):\n return\n\n # Set logical frame to requested position\n self.__logical_frame = frame\n\n def _reset(self, reset: bool = True) -> None:\n if reset:\n self._decoder.reset()\n self.__physical_frame = 0\n self.__loaded = -1\n self.__timestamp = 0\n\n def _get_next(self) -> tuple[bytes, int, int]:\n # Get next frame\n ret = self._decoder.get_next()\n self.__physical_frame += 1\n\n # Check if an error occurred\n if ret is None:\n self._reset() # Reset just to be safe\n self.seek(0)\n msg = "failed to decode next frame in WebP file"\n raise EOFError(msg)\n\n # Compute duration\n data, timestamp = ret\n duration = timestamp - self.__timestamp\n self.__timestamp = timestamp\n\n # libwebp gives frame end, adjust to start of frame\n timestamp -= duration\n return data, timestamp, duration\n\n def _seek(self, frame: int) -> None:\n if self.__physical_frame == frame:\n return # Nothing to do\n if frame < self.__physical_frame:\n self._reset() # Rewind to beginning\n while self.__physical_frame < frame:\n self._get_next() # Advance to the requested frame\n\n def load(self) -> Image.core.PixelAccess | None:\n if self.__loaded != self.__logical_frame:\n self._seek(self.__logical_frame)\n\n # We need to load the image data for this frame\n data, timestamp, duration = self._get_next()\n self.info["timestamp"] = timestamp\n self.info["duration"] = duration\n self.__loaded = self.__logical_frame\n\n # Set tile\n if self.fp and self._exclusive_fp:\n self.fp.close()\n self.fp = BytesIO(data)\n self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 0, self.rawmode)]\n\n return super().load()\n\n def load_seek(self, pos: int) -> None:\n pass\n\n def tell(self) -> int:\n return self.__logical_frame\n\n\ndef _convert_frame(im: Image.Image) -> Image.Image:\n # Make sure image mode is supported\n if im.mode not in ("RGBX", "RGBA", "RGB"):\n im = im.convert("RGBA" if im.has_transparency_data else "RGB")\n return im\n\n\ndef _save_all(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n encoderinfo = im.encoderinfo.copy()\n append_images = list(encoderinfo.get("append_images", []))\n\n # If total frame count is 1, then save using the legacy API, which\n # will preserve non-alpha modes\n total = 0\n for ims in [im] + append_images:\n total += getattr(ims, "n_frames", 1)\n if total == 1:\n _save(im, fp, filename)\n return\n\n background: int | tuple[int, ...] = (0, 0, 0, 0)\n if "background" in encoderinfo:\n background = encoderinfo["background"]\n elif "background" in im.info:\n background = im.info["background"]\n if isinstance(background, int):\n # GifImagePlugin stores a global color table index in\n # info["background"]. So it must be converted to an RGBA value\n palette = im.getpalette()\n if palette:\n r, g, b = palette[background * 3 : (background + 1) * 3]\n background = (r, g, b, 255)\n else:\n background = (background, background, background, 255)\n\n duration = im.encoderinfo.get("duration", im.info.get("duration", 0))\n loop = im.encoderinfo.get("loop", 0)\n minimize_size = im.encoderinfo.get("minimize_size", False)\n kmin = im.encoderinfo.get("kmin", None)\n kmax = im.encoderinfo.get("kmax", None)\n allow_mixed = im.encoderinfo.get("allow_mixed", False)\n verbose = False\n lossless = im.encoderinfo.get("lossless", False)\n quality = im.encoderinfo.get("quality", 80)\n alpha_quality = im.encoderinfo.get("alpha_quality", 100)\n method = im.encoderinfo.get("method", 0)\n icc_profile = im.encoderinfo.get("icc_profile") or ""\n exif = im.encoderinfo.get("exif", "")\n if isinstance(exif, Image.Exif):\n exif = exif.tobytes()\n xmp = im.encoderinfo.get("xmp", "")\n if allow_mixed:\n lossless = False\n\n # Sensible keyframe defaults are from gif2webp.c script\n if kmin is None:\n kmin = 9 if lossless else 3\n if kmax is None:\n kmax = 17 if lossless else 5\n\n # Validate background color\n if (\n not isinstance(background, (list, tuple))\n or len(background) != 4\n or not all(0 <= v < 256 for v in background)\n ):\n msg = f"Background color is not an RGBA tuple clamped to (0-255): {background}"\n raise OSError(msg)\n\n # Convert to packed uint\n bg_r, bg_g, bg_b, bg_a = background\n background = (bg_a << 24) | (bg_r << 16) | (bg_g << 8) | (bg_b << 0)\n\n # Setup the WebP animation encoder\n enc = _webp.WebPAnimEncoder(\n im.size,\n background,\n loop,\n minimize_size,\n kmin,\n kmax,\n allow_mixed,\n verbose,\n )\n\n # Add each frame\n frame_idx = 0\n timestamp = 0\n cur_idx = im.tell()\n try:\n for ims in [im] + append_images:\n # Get number of frames in this image\n nfr = getattr(ims, "n_frames", 1)\n\n for idx in range(nfr):\n ims.seek(idx)\n\n frame = _convert_frame(ims)\n\n # Append the frame to the animation encoder\n enc.add(\n frame.getim(),\n round(timestamp),\n lossless,\n quality,\n alpha_quality,\n method,\n )\n\n # Update timestamp and frame index\n if isinstance(duration, (list, tuple)):\n timestamp += duration[frame_idx]\n else:\n timestamp += duration\n frame_idx += 1\n\n finally:\n im.seek(cur_idx)\n\n # Force encoder to flush frames\n enc.add(None, round(timestamp), lossless, quality, alpha_quality, 0)\n\n # Get the final output from the encoder\n data = enc.assemble(icc_profile, exif, xmp)\n if data is None:\n msg = "cannot write file as WebP (encoder returned None)"\n raise OSError(msg)\n\n fp.write(data)\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n lossless = im.encoderinfo.get("lossless", False)\n quality = im.encoderinfo.get("quality", 80)\n alpha_quality = im.encoderinfo.get("alpha_quality", 100)\n icc_profile = im.encoderinfo.get("icc_profile") or ""\n exif = im.encoderinfo.get("exif", b"")\n if isinstance(exif, Image.Exif):\n exif = exif.tobytes()\n if exif.startswith(b"Exif\x00\x00"):\n exif = exif[6:]\n xmp = im.encoderinfo.get("xmp", "")\n method = im.encoderinfo.get("method", 4)\n exact = 1 if im.encoderinfo.get("exact") else 0\n\n im = _convert_frame(im)\n\n data = _webp.WebPEncode(\n im.getim(),\n lossless,\n float(quality),\n float(alpha_quality),\n icc_profile,\n method,\n exact,\n exif,\n xmp,\n )\n if data is None:\n msg = "cannot write file as WebP (encoder returned None)"\n raise OSError(msg)\n\n fp.write(data)\n\n\nImage.register_open(WebPImageFile.format, WebPImageFile, _accept)\nif SUPPORTED:\n Image.register_save(WebPImageFile.format, _save)\n Image.register_save_all(WebPImageFile.format, _save_all)\n Image.register_extension(WebPImageFile.format, ".webp")\n Image.register_mime(WebPImageFile.format, "image/webp")\n | .venv\Lib\site-packages\PIL\WebPImagePlugin.py | WebPImagePlugin.py | Python | 10,330 | 0.95 | 0.178125 | 0.102662 | awesome-app | 929 | 2024-08-29T23:48:01.463594 | Apache-2.0 | false | 1793e6e943b6936edb4cdfc55eedb936 |
#\n# The Python Imaging Library\n# $Id$\n#\n# WMF stub codec\n#\n# history:\n# 1996-12-14 fl Created\n# 2004-02-22 fl Turned into a stub driver\n# 2004-02-23 fl Added EMF support\n#\n# Copyright (c) Secret Labs AB 1997-2004. All rights reserved.\n# Copyright (c) Fredrik Lundh 1996.\n#\n# See the README file for information on usage and redistribution.\n#\n# WMF/EMF reference documentation:\n# https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-WMF/[MS-WMF].pdf\n# http://wvware.sourceforge.net/caolan/index.html\n# http://wvware.sourceforge.net/caolan/ora-wmf.html\nfrom __future__ import annotations\n\nfrom typing import IO\n\nfrom . import Image, ImageFile\nfrom ._binary import i16le as word\nfrom ._binary import si16le as short\nfrom ._binary import si32le as _long\n\n_handler = None\n\n\ndef register_handler(handler: ImageFile.StubHandler | None) -> None:\n """\n Install application-specific WMF image handler.\n\n :param handler: Handler object.\n """\n global _handler\n _handler = handler\n\n\nif hasattr(Image.core, "drawwmf"):\n # install default handler (windows only)\n\n class WmfHandler(ImageFile.StubHandler):\n def open(self, im: ImageFile.StubImageFile) -> None:\n im._mode = "RGB"\n self.bbox = im.info["wmf_bbox"]\n\n def load(self, im: ImageFile.StubImageFile) -> Image.Image:\n im.fp.seek(0) # rewind\n return Image.frombytes(\n "RGB",\n im.size,\n Image.core.drawwmf(im.fp.read(), im.size, self.bbox),\n "raw",\n "BGR",\n (im.size[0] * 3 + 3) & -4,\n -1,\n )\n\n register_handler(WmfHandler())\n\n#\n# --------------------------------------------------------------------\n# Read WMF file\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))\n\n\n##\n# Image plugin for Windows metafiles.\n\n\nclass WmfStubImageFile(ImageFile.StubImageFile):\n format = "WMF"\n format_description = "Windows Metafile"\n\n def _open(self) -> None:\n # check placable header\n s = self.fp.read(44)\n\n if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):\n # placeable windows metafile\n\n # get units per inch\n inch = word(s, 14)\n if inch == 0:\n msg = "Invalid inch"\n raise ValueError(msg)\n self._inch: tuple[float, float] = inch, inch\n\n # get bounding box\n x0 = short(s, 6)\n y0 = short(s, 8)\n x1 = short(s, 10)\n y1 = short(s, 12)\n\n # normalize size to 72 dots per inch\n self.info["dpi"] = 72\n size = (\n (x1 - x0) * self.info["dpi"] // inch,\n (y1 - y0) * self.info["dpi"] // inch,\n )\n\n self.info["wmf_bbox"] = x0, y0, x1, y1\n\n # sanity check (standard metafile header)\n if s[22:26] != b"\x01\x00\t\x00":\n msg = "Unsupported WMF file format"\n raise SyntaxError(msg)\n\n elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":\n # enhanced metafile\n\n # get bounding box\n x0 = _long(s, 8)\n y0 = _long(s, 12)\n x1 = _long(s, 16)\n y1 = _long(s, 20)\n\n # get frame (in 0.01 millimeter units)\n frame = _long(s, 24), _long(s, 28), _long(s, 32), _long(s, 36)\n\n size = x1 - x0, y1 - y0\n\n # calculate dots per inch from bbox and frame\n xdpi = 2540.0 * (x1 - x0) / (frame[2] - frame[0])\n ydpi = 2540.0 * (y1 - y0) / (frame[3] - frame[1])\n\n self.info["wmf_bbox"] = x0, y0, x1, y1\n\n if xdpi == ydpi:\n self.info["dpi"] = xdpi\n else:\n self.info["dpi"] = xdpi, ydpi\n self._inch = xdpi, ydpi\n\n else:\n msg = "Unsupported file format"\n raise SyntaxError(msg)\n\n self._mode = "RGB"\n self._size = size\n\n loader = self._load()\n if loader:\n loader.open(self)\n\n def _load(self) -> ImageFile.StubHandler | None:\n return _handler\n\n def load(\n self, dpi: float | tuple[float, float] | None = None\n ) -> Image.core.PixelAccess | None:\n if dpi is not None:\n self.info["dpi"] = dpi\n x0, y0, x1, y1 = self.info["wmf_bbox"]\n if not isinstance(dpi, tuple):\n dpi = dpi, dpi\n self._size = (\n int((x1 - x0) * dpi[0] / self._inch[0]),\n int((y1 - y0) * dpi[1] / self._inch[1]),\n )\n return super().load()\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if _handler is None or not hasattr(_handler, "save"):\n msg = "WMF save handler not installed"\n raise OSError(msg)\n _handler.save(im, fp, filename)\n\n\n#\n# --------------------------------------------------------------------\n# Registry stuff\n\n\nImage.register_open(WmfStubImageFile.format, WmfStubImageFile, _accept)\nImage.register_save(WmfStubImageFile.format, _save)\n\nImage.register_extensions(WmfStubImageFile.format, [".wmf", ".emf"])\n | .venv\Lib\site-packages\PIL\WmfImagePlugin.py | WmfImagePlugin.py | Python | 5,429 | 0.95 | 0.112903 | 0.274648 | awesome-app | 15 | 2024-07-08T07:36:08.243447 | MIT | false | 2cda0f00f11b89d6be778ed9f9f19f5f |
#\n# The Python Imaging Library.\n# $Id$\n#\n# XBM File handling\n#\n# History:\n# 1995-09-08 fl Created\n# 1996-11-01 fl Added save support\n# 1997-07-07 fl Made header parser more tolerant\n# 1997-07-22 fl Fixed yet another parser bug\n# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)\n# 2001-05-13 fl Added hotspot handling (based on code from Bernhard Herzog)\n# 2004-02-24 fl Allow some whitespace before first #define\n#\n# Copyright (c) 1997-2004 by Secret Labs AB\n# Copyright (c) 1996-1997 by Fredrik Lundh\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport re\nfrom typing import IO\n\nfrom . import Image, ImageFile\n\n# XBM header\nxbm_head = re.compile(\n rb"\s*#define[ \t]+.*_width[ \t]+(?P<width>[0-9]+)[\r\n]+"\n b"#define[ \t]+.*_height[ \t]+(?P<height>[0-9]+)[\r\n]+"\n b"(?P<hotspot>"\n b"#define[ \t]+[^_]*_x_hot[ \t]+(?P<xhot>[0-9]+)[\r\n]+"\n b"#define[ \t]+[^_]*_y_hot[ \t]+(?P<yhot>[0-9]+)[\r\n]+"\n b")?"\n rb"[\000-\377]*_bits\[]"\n)\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.lstrip().startswith(b"#define")\n\n\n##\n# Image plugin for X11 bitmaps.\n\n\nclass XbmImageFile(ImageFile.ImageFile):\n format = "XBM"\n format_description = "X11 Bitmap"\n\n def _open(self) -> None:\n assert self.fp is not None\n\n m = xbm_head.match(self.fp.read(512))\n\n if not m:\n msg = "not a XBM file"\n raise SyntaxError(msg)\n\n xsize = int(m.group("width"))\n ysize = int(m.group("height"))\n\n if m.group("hotspot"):\n self.info["hotspot"] = (int(m.group("xhot")), int(m.group("yhot")))\n\n self._mode = "1"\n self._size = xsize, ysize\n\n self.tile = [ImageFile._Tile("xbm", (0, 0) + self.size, m.end())]\n\n\ndef _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:\n if im.mode != "1":\n msg = f"cannot write mode {im.mode} as XBM"\n raise OSError(msg)\n\n fp.write(f"#define im_width {im.size[0]}\n".encode("ascii"))\n fp.write(f"#define im_height {im.size[1]}\n".encode("ascii"))\n\n hotspot = im.encoderinfo.get("hotspot")\n if hotspot:\n fp.write(f"#define im_x_hot {hotspot[0]}\n".encode("ascii"))\n fp.write(f"#define im_y_hot {hotspot[1]}\n".encode("ascii"))\n\n fp.write(b"static char im_bits[] = {\n")\n\n ImageFile._save(im, fp, [ImageFile._Tile("xbm", (0, 0) + im.size)])\n\n fp.write(b"};\n")\n\n\nImage.register_open(XbmImageFile.format, XbmImageFile, _accept)\nImage.register_save(XbmImageFile.format, _save)\n\nImage.register_extension(XbmImageFile.format, ".xbm")\n\nImage.register_mime(XbmImageFile.format, "image/xbm")\n | .venv\Lib\site-packages\PIL\XbmImagePlugin.py | XbmImagePlugin.py | Python | 2,767 | 0.95 | 0.102041 | 0.323944 | node-utils | 205 | 2024-10-05T18:15:23.848827 | Apache-2.0 | false | 42ef469d3beeabc4db6207ff6c09df01 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# XPM File handling\n#\n# History:\n# 1996-12-29 fl Created\n# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.7)\n#\n# Copyright (c) Secret Labs AB 1997-2001.\n# Copyright (c) Fredrik Lundh 1996-2001.\n#\n# See the README file for information on usage and redistribution.\n#\nfrom __future__ import annotations\n\nimport re\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import o8\n\n# XPM header\nxpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)')\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(b"/* XPM */")\n\n\n##\n# Image plugin for X11 pixel maps.\n\n\nclass XpmImageFile(ImageFile.ImageFile):\n format = "XPM"\n format_description = "X11 Pixel Map"\n\n def _open(self) -> None:\n assert self.fp is not None\n if not _accept(self.fp.read(9)):\n msg = "not an XPM file"\n raise SyntaxError(msg)\n\n # skip forward to next string\n while True:\n line = self.fp.readline()\n if not line:\n msg = "broken XPM file"\n raise SyntaxError(msg)\n m = xpm_head.match(line)\n if m:\n break\n\n self._size = int(m.group(1)), int(m.group(2))\n\n palette_length = int(m.group(3))\n bpp = int(m.group(4))\n\n #\n # load palette description\n\n palette = {}\n\n for _ in range(palette_length):\n line = self.fp.readline().rstrip()\n\n c = line[1 : bpp + 1]\n s = line[bpp + 1 : -2].split()\n\n for i in range(0, len(s), 2):\n if s[i] == b"c":\n # process colour key\n rgb = s[i + 1]\n if rgb == b"None":\n self.info["transparency"] = c\n elif rgb.startswith(b"#"):\n rgb_int = int(rgb[1:], 16)\n palette[c] = (\n o8((rgb_int >> 16) & 255)\n + o8((rgb_int >> 8) & 255)\n + o8(rgb_int & 255)\n )\n else:\n # unknown colour\n msg = "cannot read this XPM file"\n raise ValueError(msg)\n break\n\n else:\n # missing colour key\n msg = "cannot read this XPM file"\n raise ValueError(msg)\n\n args: tuple[int, dict[bytes, bytes] | tuple[bytes, ...]]\n if palette_length > 256:\n self._mode = "RGB"\n args = (bpp, palette)\n else:\n self._mode = "P"\n self.palette = ImagePalette.raw("RGB", b"".join(palette.values()))\n args = (bpp, tuple(palette.keys()))\n\n self.tile = [ImageFile._Tile("xpm", (0, 0) + self.size, self.fp.tell(), args)]\n\n def load_read(self, read_bytes: int) -> bytes:\n #\n # load all image data in one chunk\n\n xsize, ysize = self.size\n\n assert self.fp is not None\n s = [self.fp.readline()[1 : xsize + 1].ljust(xsize) for i in range(ysize)]\n\n return b"".join(s)\n\n\nclass XpmDecoder(ImageFile.PyDecoder):\n _pulls_fd = True\n\n def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:\n assert self.fd is not None\n\n data = bytearray()\n bpp, palette = self.args\n dest_length = self.state.xsize * self.state.ysize\n if self.mode == "RGB":\n dest_length *= 3\n pixel_header = False\n while len(data) < dest_length:\n line = self.fd.readline()\n if not line:\n break\n if line.rstrip() == b"/* pixels */" and not pixel_header:\n pixel_header = True\n continue\n line = b'"'.join(line.split(b'"')[1:-1])\n for i in range(0, len(line), bpp):\n key = line[i : i + bpp]\n if self.mode == "RGB":\n data += palette[key]\n else:\n data += o8(palette.index(key))\n self.set_as_raw(bytes(data))\n return -1, 0\n\n\n#\n# Registry\n\n\nImage.register_open(XpmImageFile.format, XpmImageFile, _accept)\nImage.register_decoder("xpm", XpmDecoder)\n\nImage.register_extension(XpmImageFile.format, ".xpm")\n\nImage.register_mime(XpmImageFile.format, "image/xpm")\n | .venv\Lib\site-packages\PIL\XpmImagePlugin.py | XpmImagePlugin.py | Python | 4,557 | 0.95 | 0.152866 | 0.229508 | vue-tools | 775 | 2024-04-26T17:15:45.005725 | MIT | false | dca9cdb047639fda30d7290684a04738 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# XV Thumbnail file handler by Charles E. "Gene" Cash\n# (gcash@magicnet.net)\n#\n# see xvcolor.c and xvbrowse.c in the sources to John Bradley's XV,\n# available from ftp://ftp.cis.upenn.edu/pub/xv/\n#\n# history:\n# 98-08-15 cec created (b/w only)\n# 98-12-09 cec added color palette\n# 98-12-28 fl added to PIL (with only a few very minor modifications)\n#\n# To do:\n# FIXME: make save work (this requires quantization support)\n#\nfrom __future__ import annotations\n\nfrom . import Image, ImageFile, ImagePalette\nfrom ._binary import o8\n\n_MAGIC = b"P7 332"\n\n# standard color palette for thumbnails (RGB332)\nPALETTE = b""\nfor r in range(8):\n for g in range(8):\n for b in range(4):\n PALETTE = PALETTE + (\n o8((r * 255) // 7) + o8((g * 255) // 7) + o8((b * 255) // 3)\n )\n\n\ndef _accept(prefix: bytes) -> bool:\n return prefix.startswith(_MAGIC)\n\n\n##\n# Image plugin for XV thumbnail images.\n\n\nclass XVThumbImageFile(ImageFile.ImageFile):\n format = "XVThumb"\n format_description = "XV thumbnail image"\n\n def _open(self) -> None:\n # check magic\n assert self.fp is not None\n\n if not _accept(self.fp.read(6)):\n msg = "not an XV thumbnail file"\n raise SyntaxError(msg)\n\n # Skip to beginning of next line\n self.fp.readline()\n\n # skip info comments\n while True:\n s = self.fp.readline()\n if not s:\n msg = "Unexpected EOF reading XV thumbnail file"\n raise SyntaxError(msg)\n if s[0] != 35: # ie. when not a comment: '#'\n break\n\n # parse header line (already read)\n s = s.strip().split()\n\n self._mode = "P"\n self._size = int(s[0]), int(s[1])\n\n self.palette = ImagePalette.raw("RGB", PALETTE)\n\n self.tile = [\n ImageFile._Tile("raw", (0, 0) + self.size, self.fp.tell(), self.mode)\n ]\n\n\n# --------------------------------------------------------------------\n\nImage.register_open(XVThumbImageFile.format, XVThumbImageFile, _accept)\n | .venv\Lib\site-packages\PIL\XVThumbImagePlugin.py | XVThumbImagePlugin.py | Python | 2,198 | 0.95 | 0.144578 | 0.412698 | python-kit | 485 | 2024-04-16T05:56:47.348281 | Apache-2.0 | false | 6577df64311d49465bfc6ab2640bb8d7 |
from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_avif.pyi | _avif.pyi | Other | 66 | 0.65 | 0.333333 | 0 | vue-tools | 21 | 2023-09-29T02:05:21.077909 | Apache-2.0 | false | 84a27291937d76e46b277653002601f2 |
#\n# The Python Imaging Library.\n# $Id$\n#\n# Binary input/output support routines.\n#\n# Copyright (c) 1997-2003 by Secret Labs AB\n# Copyright (c) 1995-2003 by Fredrik Lundh\n# Copyright (c) 2012 by Brian Crowell\n#\n# See the README file for information on usage and redistribution.\n#\n\n\n"""Binary input/output support routines."""\nfrom __future__ import annotations\n\nfrom struct import pack, unpack_from\n\n\ndef i8(c: bytes) -> int:\n return c[0]\n\n\ndef o8(i: int) -> bytes:\n return bytes((i & 255,))\n\n\n# Input, le = little endian, be = big endian\ndef i16le(c: bytes, o: int = 0) -> int:\n """\n Converts a 2-bytes (16 bits) string to an unsigned integer.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from("<H", c, o)[0]\n\n\ndef si16le(c: bytes, o: int = 0) -> int:\n """\n Converts a 2-bytes (16 bits) string to a signed integer.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from("<h", c, o)[0]\n\n\ndef si16be(c: bytes, o: int = 0) -> int:\n """\n Converts a 2-bytes (16 bits) string to a signed integer, big endian.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from(">h", c, o)[0]\n\n\ndef i32le(c: bytes, o: int = 0) -> int:\n """\n Converts a 4-bytes (32 bits) string to an unsigned integer.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from("<I", c, o)[0]\n\n\ndef si32le(c: bytes, o: int = 0) -> int:\n """\n Converts a 4-bytes (32 bits) string to a signed integer.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from("<i", c, o)[0]\n\n\ndef si32be(c: bytes, o: int = 0) -> int:\n """\n Converts a 4-bytes (32 bits) string to a signed integer, big endian.\n\n :param c: string containing bytes to convert\n :param o: offset of bytes to convert in string\n """\n return unpack_from(">i", c, o)[0]\n\n\ndef i16be(c: bytes, o: int = 0) -> int:\n return unpack_from(">H", c, o)[0]\n\n\ndef i32be(c: bytes, o: int = 0) -> int:\n return unpack_from(">I", c, o)[0]\n\n\n# Output, le = little endian, be = big endian\ndef o16le(i: int) -> bytes:\n return pack("<H", i)\n\n\ndef o32le(i: int) -> bytes:\n return pack("<I", i)\n\n\ndef o16be(i: int) -> bytes:\n return pack(">H", i)\n\n\ndef o32be(i: int) -> bytes:\n return pack(">I", i)\n | .venv\Lib\site-packages\PIL\_binary.py | _binary.py | Python | 2,662 | 0.95 | 0.133929 | 0.186667 | node-utils | 480 | 2024-06-27T13:37:23.733368 | Apache-2.0 | false | 1cf614dc7ee53ec8ce789da4b74b69b8 |
from __future__ import annotations\n\nimport warnings\n\nfrom . import __version__\n\n\ndef deprecate(\n deprecated: str,\n when: int | None,\n replacement: str | None = None,\n *,\n action: str | None = None,\n plural: bool = False,\n stacklevel: int = 3,\n) -> None:\n """\n Deprecations helper.\n\n :param deprecated: Name of thing to be deprecated.\n :param when: Pillow major version to be removed in.\n :param replacement: Name of replacement.\n :param action: Instead of "replacement", give a custom call to action\n e.g. "Upgrade to new thing".\n :param plural: if the deprecated thing is plural, needing "are" instead of "is".\n\n Usually of the form:\n\n "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).\n Use [replacement] instead."\n\n You can leave out the replacement sentence:\n\n "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd)"\n\n Or with another call to action:\n\n "[deprecated] is deprecated and will be removed in Pillow [when] (yyyy-mm-dd).\n [action]."\n """\n\n is_ = "are" if plural else "is"\n\n if when is None:\n removed = "a future version"\n elif when <= int(__version__.split(".")[0]):\n msg = f"{deprecated} {is_} deprecated and should be removed."\n raise RuntimeError(msg)\n elif when == 12:\n removed = "Pillow 12 (2025-10-15)"\n elif when == 13:\n removed = "Pillow 13 (2026-10-15)"\n else:\n msg = f"Unknown removal version: {when}. Update {__name__}?"\n raise ValueError(msg)\n\n if replacement and action:\n msg = "Use only one of 'replacement' and 'action'"\n raise ValueError(msg)\n\n if replacement:\n action = f". Use {replacement} instead."\n elif action:\n action = f". {action.rstrip('.')}."\n else:\n action = ""\n\n warnings.warn(\n f"{deprecated} {is_} deprecated and will be removed in {removed}{action}",\n DeprecationWarning,\n stacklevel=stacklevel,\n )\n | .venv\Lib\site-packages\PIL\_deprecate.py | _deprecate.py | Python | 2,106 | 0.85 | 0.083333 | 0.017857 | node-utils | 761 | 2024-11-28T01:19:57.310639 | MIT | false | b0c8bb1e37401408586fd25003a467cc |
from typing import Any\n\nclass ImagingCore:\n def __getitem__(self, index: int) -> float: ...\n def __getattr__(self, name: str) -> Any: ...\n\nclass ImagingFont:\n def __getattr__(self, name: str) -> Any: ...\n\nclass ImagingDraw:\n def __getattr__(self, name: str) -> Any: ...\n\nclass PixelAccess:\n def __getitem__(self, xy: tuple[int, int]) -> float | tuple[int, ...]: ...\n def __setitem__(\n self, xy: tuple[int, int], color: float | tuple[int, ...]\n ) -> None: ...\n\nclass ImagingDecoder:\n def __getattr__(self, name: str) -> Any: ...\n\nclass ImagingEncoder:\n def __getattr__(self, name: str) -> Any: ...\n\nclass _Outline:\n def close(self) -> None: ...\n def __getattr__(self, name: str) -> Any: ...\n\ndef font(image: ImagingCore, glyphdata: bytes) -> ImagingFont: ...\ndef outline() -> _Outline: ...\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_imaging.pyi | _imaging.pyi | Other | 899 | 0.85 | 0.645161 | 0 | react-lib | 401 | 2024-02-01T05:07:12.455286 | GPL-3.0 | false | adcd7477c0405689fea52da73ec121a5 |
import datetime\nimport sys\nfrom typing import Literal, SupportsFloat, TypedDict\n\nfrom ._typing import CapsuleType\n\nlittlecms_version: str | None\n\n_Tuple3f = tuple[float, float, float]\n_Tuple2x3f = tuple[_Tuple3f, _Tuple3f]\n_Tuple3x3f = tuple[_Tuple3f, _Tuple3f, _Tuple3f]\n\nclass _IccMeasurementCondition(TypedDict):\n observer: int\n backing: _Tuple3f\n geo: str\n flare: float\n illuminant_type: str\n\nclass _IccViewingCondition(TypedDict):\n illuminant: _Tuple3f\n surround: _Tuple3f\n illuminant_type: str\n\nclass CmsProfile:\n @property\n def rendering_intent(self) -> int: ...\n @property\n def creation_date(self) -> datetime.datetime | None: ...\n @property\n def copyright(self) -> str | None: ...\n @property\n def target(self) -> str | None: ...\n @property\n def manufacturer(self) -> str | None: ...\n @property\n def model(self) -> str | None: ...\n @property\n def profile_description(self) -> str | None: ...\n @property\n def screening_description(self) -> str | None: ...\n @property\n def viewing_condition(self) -> str | None: ...\n @property\n def version(self) -> float: ...\n @property\n def icc_version(self) -> int: ...\n @property\n def attributes(self) -> int: ...\n @property\n def header_flags(self) -> int: ...\n @property\n def header_manufacturer(self) -> str: ...\n @property\n def header_model(self) -> str: ...\n @property\n def device_class(self) -> str: ...\n @property\n def connection_space(self) -> str: ...\n @property\n def xcolor_space(self) -> str: ...\n @property\n def profile_id(self) -> bytes: ...\n @property\n def is_matrix_shaper(self) -> bool: ...\n @property\n def technology(self) -> str | None: ...\n @property\n def colorimetric_intent(self) -> str | None: ...\n @property\n def perceptual_rendering_intent_gamut(self) -> str | None: ...\n @property\n def saturation_rendering_intent_gamut(self) -> str | None: ...\n @property\n def red_colorant(self) -> _Tuple2x3f | None: ...\n @property\n def green_colorant(self) -> _Tuple2x3f | None: ...\n @property\n def blue_colorant(self) -> _Tuple2x3f | None: ...\n @property\n def red_primary(self) -> _Tuple2x3f | None: ...\n @property\n def green_primary(self) -> _Tuple2x3f | None: ...\n @property\n def blue_primary(self) -> _Tuple2x3f | None: ...\n @property\n def media_white_point_temperature(self) -> float | None: ...\n @property\n def media_white_point(self) -> _Tuple2x3f | None: ...\n @property\n def media_black_point(self) -> _Tuple2x3f | None: ...\n @property\n def luminance(self) -> _Tuple2x3f | None: ...\n @property\n def chromatic_adaptation(self) -> tuple[_Tuple3x3f, _Tuple3x3f] | None: ...\n @property\n def chromaticity(self) -> _Tuple3x3f | None: ...\n @property\n def colorant_table(self) -> list[str] | None: ...\n @property\n def colorant_table_out(self) -> list[str] | None: ...\n @property\n def intent_supported(self) -> dict[int, tuple[bool, bool, bool]] | None: ...\n @property\n def clut(self) -> dict[int, tuple[bool, bool, bool]] | None: ...\n @property\n def icc_measurement_condition(self) -> _IccMeasurementCondition | None: ...\n @property\n def icc_viewing_condition(self) -> _IccViewingCondition | None: ...\n def is_intent_supported(self, intent: int, direction: int, /) -> int: ...\n\nclass CmsTransform:\n def apply(self, id_in: CapsuleType, id_out: CapsuleType) -> int: ...\n\ndef profile_open(profile: str, /) -> CmsProfile: ...\ndef profile_frombytes(profile: bytes, /) -> CmsProfile: ...\ndef profile_tobytes(profile: CmsProfile, /) -> bytes: ...\ndef buildTransform(\n input_profile: CmsProfile,\n output_profile: CmsProfile,\n in_mode: str,\n out_mode: str,\n rendering_intent: int = 0,\n cms_flags: int = 0,\n /,\n) -> CmsTransform: ...\ndef buildProofTransform(\n input_profile: CmsProfile,\n output_profile: CmsProfile,\n proof_profile: CmsProfile,\n in_mode: str,\n out_mode: str,\n rendering_intent: int = 0,\n proof_intent: int = 0,\n cms_flags: int = 0,\n /,\n) -> CmsTransform: ...\ndef createProfile(\n color_space: Literal["LAB", "XYZ", "sRGB"], color_temp: SupportsFloat = 0.0, /\n) -> CmsProfile: ...\n\nif sys.platform == "win32":\n def get_display_profile_win32(handle: int = 0, is_dc: int = 0, /) -> str | None: ...\n | .venv\Lib\site-packages\PIL\_imagingcms.pyi | _imagingcms.pyi | Other | 4,532 | 0.85 | 0.391608 | 0 | node-utils | 422 | 2023-10-25T23:42:42.559463 | MIT | false | f9b475413acc6dfac34e62c3c26a5a11 |
from typing import Any, Callable\n\nfrom . import ImageFont, _imaging\n\nclass Font:\n @property\n def family(self) -> str | None: ...\n @property\n def style(self) -> str | None: ...\n @property\n def ascent(self) -> int: ...\n @property\n def descent(self) -> int: ...\n @property\n def height(self) -> int: ...\n @property\n def x_ppem(self) -> int: ...\n @property\n def y_ppem(self) -> int: ...\n @property\n def glyphs(self) -> int: ...\n def render(\n self,\n string: str | bytes,\n fill: Callable[[int, int], _imaging.ImagingCore],\n mode: str,\n dir: str | None,\n features: list[str] | None,\n lang: str | None,\n stroke_width: float,\n stroke_filled: bool,\n anchor: str | None,\n foreground_ink_long: int,\n start: tuple[float, float],\n /,\n ) -> tuple[_imaging.ImagingCore, tuple[int, int]]: ...\n def getsize(\n self,\n string: str | bytes | bytearray,\n mode: str,\n dir: str | None,\n features: list[str] | None,\n lang: str | None,\n anchor: str | None,\n /,\n ) -> tuple[tuple[int, int], tuple[int, int]]: ...\n def getlength(\n self,\n string: str | bytes,\n mode: str,\n dir: str | None,\n features: list[str] | None,\n lang: str | None,\n /,\n ) -> float: ...\n def getvarnames(self) -> list[bytes]: ...\n def getvaraxes(self) -> list[ImageFont.Axis]: ...\n def setvarname(self, instance_index: int, /) -> None: ...\n def setvaraxes(self, axes: list[float], /) -> None: ...\n\ndef getfont(\n filename: str | bytes,\n size: float,\n index: int,\n encoding: str,\n font_bytes: bytes,\n layout_engine: int,\n) -> Font: ...\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_imagingft.pyi | _imagingft.pyi | Other | 1,875 | 0.85 | 0.26087 | 0 | node-utils | 681 | 2024-09-02T04:03:22.371870 | GPL-3.0 | false | 0210db52ee8036fe8056f9283a24e9ee |
MZ | .venv\Lib\site-packages\PIL\_imagingmath.cp313-win_amd64.pyd | _imagingmath.cp313-win_amd64.pyd | Other | 25,088 | 0.8 | 0 | 0.006993 | awesome-app | 359 | 2023-07-14T03:24:41.130738 | BSD-3-Clause | false | eced3ef4fa1e5bece0d08e5e2ce30546 |
from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_imagingmath.pyi | _imagingmath.pyi | Other | 66 | 0.65 | 0.333333 | 0 | react-lib | 574 | 2023-09-21T07:05:34.388445 | GPL-3.0 | false | 84a27291937d76e46b277653002601f2 |
MZ | .venv\Lib\site-packages\PIL\_imagingmorph.cp313-win_amd64.pyd | _imagingmorph.cp313-win_amd64.pyd | Other | 13,824 | 0.8 | 0.012658 | 0.012658 | react-lib | 452 | 2025-02-18T00:55:55.933476 | GPL-3.0 | false | 85edf97e5147727a0c88f40cc7ffffce |
from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_imagingmorph.pyi | _imagingmorph.pyi | Other | 66 | 0.65 | 0.333333 | 0 | node-utils | 876 | 2023-09-25T09:44:10.003633 | GPL-3.0 | false | 84a27291937d76e46b277653002601f2 |
MZ | .venv\Lib\site-packages\PIL\_imagingtk.cp313-win_amd64.pyd | _imagingtk.cp313-win_amd64.pyd | Other | 14,848 | 0.95 | 0.012987 | 0.038961 | node-utils | 808 | 2024-03-29T08:10:31.495601 | BSD-3-Clause | false | e29d6bf4d3816b7444cba657cb5068f7 |
from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_imagingtk.pyi | _imagingtk.pyi | Other | 66 | 0.65 | 0.333333 | 0 | node-utils | 499 | 2024-02-15T14:21:59.078845 | BSD-3-Clause | false | 84a27291937d76e46b277653002601f2 |
"""Find compiled module linking to Tcl / Tk libraries"""\n\nfrom __future__ import annotations\n\nimport sys\nimport tkinter\n\ntk = getattr(tkinter, "_tkinter")\n\ntry:\n if hasattr(sys, "pypy_find_executable"):\n TKINTER_LIB = tk.tklib_cffi.__file__\n else:\n TKINTER_LIB = tk.__file__\nexcept AttributeError:\n # _tkinter may be compiled directly into Python, in which case __file__ is\n # not available. load_tkinter_funcs will check the binary first in any case.\n TKINTER_LIB = None\n\ntk_version = str(tkinter.TkVersion)\n | .venv\Lib\site-packages\PIL\_tkinter_finder.py | _tkinter_finder.py | Python | 558 | 0.95 | 0.1 | 0.133333 | react-lib | 955 | 2023-10-27T19:19:11.037041 | MIT | false | f0a16faa8727bda6fa3d7e3e6609561f |
from __future__ import annotations\n\nimport os\nimport sys\nfrom collections.abc import Sequence\nfrom typing import Any, Protocol, TypeVar, Union\n\nTYPE_CHECKING = False\nif TYPE_CHECKING:\n from numbers import _IntegralLike as IntegralLike\n\n try:\n import numpy.typing as npt\n\n NumpyArray = npt.NDArray[Any] # requires numpy>=1.21\n except (ImportError, AttributeError):\n pass\n\nif sys.version_info >= (3, 13):\n from types import CapsuleType\nelse:\n CapsuleType = object\n\nif sys.version_info >= (3, 12):\n from collections.abc import Buffer\nelse:\n Buffer = Any\n\nif sys.version_info >= (3, 10):\n from typing import TypeGuard\nelse:\n try:\n from typing_extensions import TypeGuard\n except ImportError:\n\n class TypeGuard: # type: ignore[no-redef]\n def __class_getitem__(cls, item: Any) -> type[bool]:\n return bool\n\n\nCoords = Union[Sequence[float], Sequence[Sequence[float]]]\n\n\n_T_co = TypeVar("_T_co", covariant=True)\n\n\nclass SupportsRead(Protocol[_T_co]):\n def read(self, length: int = ..., /) -> _T_co: ...\n\n\nStrOrBytesPath = Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]\n\n\n__all__ = ["Buffer", "IntegralLike", "StrOrBytesPath", "SupportsRead", "TypeGuard"]\n | .venv\Lib\site-packages\PIL\_typing.py | _typing.py | Python | 1,305 | 0.95 | 0.185185 | 0 | node-utils | 274 | 2024-05-08T00:27:26.099381 | MIT | false | 4d270010a733244f6f171850f743b6de |
from __future__ import annotations\n\nimport os\nfrom typing import Any, NoReturn\n\nfrom ._typing import StrOrBytesPath, TypeGuard\n\n\ndef is_path(f: Any) -> TypeGuard[StrOrBytesPath]:\n return isinstance(f, (bytes, str, os.PathLike))\n\n\nclass DeferredError:\n def __init__(self, ex: BaseException):\n self.ex = ex\n\n def __getattr__(self, elt: str) -> NoReturn:\n raise self.ex\n\n @staticmethod\n def new(ex: BaseException) -> Any:\n """\n Creates an object that raises the wrapped exception ``ex`` when used,\n and casts it to :py:obj:`~typing.Any` type.\n """\n return DeferredError(ex)\n | .venv\Lib\site-packages\PIL\_util.py | _util.py | Python | 661 | 0.85 | 0.192308 | 0 | node-utils | 485 | 2025-01-03T13:50:38.131798 | GPL-3.0 | false | 559355566951f9dc37d17fc2bc7dc785 |
# Master version for Pillow\nfrom __future__ import annotations\n\n__version__ = "11.3.0"\n | .venv\Lib\site-packages\PIL\_version.py | _version.py | Python | 91 | 0.75 | 0.25 | 0.333333 | python-kit | 679 | 2024-01-11T09:50:54.677854 | MIT | false | c1e3e7d3ccf4613335222106c03f1469 |
from typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n | .venv\Lib\site-packages\PIL\_webp.pyi | _webp.pyi | Other | 66 | 0.65 | 0.333333 | 0 | awesome-app | 245 | 2025-04-20T07:33:13.698011 | MIT | false | 84a27291937d76e46b277653002601f2 |
"""Pillow (Fork of the Python Imaging Library)\n\nPillow is the friendly PIL fork by Jeffrey A. Clark and contributors.\n https://github.com/python-pillow/Pillow/\n\nPillow is forked from PIL 1.1.7.\n\nPIL is the Python Imaging Library by Fredrik Lundh and contributors.\nCopyright (c) 1999 by Secret Labs AB.\n\nUse PIL.__version__ for this Pillow version.\n\n;-)\n"""\n\nfrom __future__ import annotations\n\nfrom . import _version\n\n# VERSION was removed in Pillow 6.0.0.\n# PILLOW_VERSION was removed in Pillow 9.0.0.\n# Use __version__ instead.\n__version__ = _version.__version__\ndel _version\n\n\n_plugins = [\n "AvifImagePlugin",\n "BlpImagePlugin",\n "BmpImagePlugin",\n "BufrStubImagePlugin",\n "CurImagePlugin",\n "DcxImagePlugin",\n "DdsImagePlugin",\n "EpsImagePlugin",\n "FitsImagePlugin",\n "FliImagePlugin",\n "FpxImagePlugin",\n "FtexImagePlugin",\n "GbrImagePlugin",\n "GifImagePlugin",\n "GribStubImagePlugin",\n "Hdf5StubImagePlugin",\n "IcnsImagePlugin",\n "IcoImagePlugin",\n "ImImagePlugin",\n "ImtImagePlugin",\n "IptcImagePlugin",\n "JpegImagePlugin",\n "Jpeg2KImagePlugin",\n "McIdasImagePlugin",\n "MicImagePlugin",\n "MpegImagePlugin",\n "MpoImagePlugin",\n "MspImagePlugin",\n "PalmImagePlugin",\n "PcdImagePlugin",\n "PcxImagePlugin",\n "PdfImagePlugin",\n "PixarImagePlugin",\n "PngImagePlugin",\n "PpmImagePlugin",\n "PsdImagePlugin",\n "QoiImagePlugin",\n "SgiImagePlugin",\n "SpiderImagePlugin",\n "SunImagePlugin",\n "TgaImagePlugin",\n "TiffImagePlugin",\n "WebPImagePlugin",\n "WmfImagePlugin",\n "XbmImagePlugin",\n "XpmImagePlugin",\n "XVThumbImagePlugin",\n]\n\n\nclass UnidentifiedImageError(OSError):\n """\n Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.\n\n If a PNG image raises this error, setting :data:`.ImageFile.LOAD_TRUNCATED_IMAGES`\n to true may allow the image to be opened after all. The setting will ignore missing\n data and checksum failures.\n """\n\n pass\n | .venv\Lib\site-packages\PIL\__init__.py | __init__.py | Python | 2,118 | 0.95 | 0.034483 | 0.041096 | vue-tools | 560 | 2025-04-26T20:53:47.199006 | MIT | false | ad0f26127bb0f8277b47501f0f210c03 |
from __future__ import annotations\n\nimport sys\n\nfrom .features import pilinfo\n\npilinfo(supported_formats="--report" not in sys.argv)\n | .venv\Lib\site-packages\PIL\__main__.py | __main__.py | Python | 140 | 0.85 | 0 | 0 | vue-tools | 547 | 2024-03-08T20:42:54.848083 | BSD-3-Clause | false | edaf137bfd9a43d4230a020254ca1675 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\AvifImagePlugin.cpython-313.pyc | AvifImagePlugin.cpython-313.pyc | Other | 12,042 | 0.8 | 0 | 0 | node-utils | 260 | 2024-07-10T01:57:27.841107 | GPL-3.0 | false | 8f6e4b2b2ede79ad4951440d466d02a9 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\BdfFontFile.cpython-313.pyc | BdfFontFile.cpython-313.pyc | Other | 4,331 | 0.8 | 0.019608 | 0 | python-kit | 283 | 2025-03-07T10:53:40.057558 | BSD-3-Clause | false | 86379587f819fc119a1c07063dd38e2f |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\BlpImagePlugin.cpython-313.pyc | BlpImagePlugin.cpython-313.pyc | Other | 24,440 | 0.8 | 0.019608 | 0.021277 | node-utils | 129 | 2023-08-05T13:46:13.036605 | Apache-2.0 | false | 6eb49eed4a55c3a21404ea22f47e1095 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\BmpImagePlugin.cpython-313.pyc | BmpImagePlugin.cpython-313.pyc | Other | 18,540 | 0.8 | 0.011696 | 0.006024 | awesome-app | 539 | 2024-07-26T18:12:32.566921 | MIT | false | 78fbe1b14e787725131ef144de9c14bd |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\BufrStubImagePlugin.cpython-313.pyc | BufrStubImagePlugin.cpython-313.pyc | Other | 2,752 | 0.8 | 0 | 0 | vue-tools | 981 | 2024-09-26T21:25:15.559261 | BSD-3-Clause | false | ec4d214c48ba29a1818bb8fb941dd303 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\ContainerIO.cpython-313.pyc | ContainerIO.cpython-313.pyc | Other | 6,915 | 0.8 | 0.054054 | 0 | react-lib | 517 | 2025-01-10T19:17:26.115944 | GPL-3.0 | false | f4a42ba2408f7ee5c1a4fdeae730859e |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\CurImagePlugin.cpython-313.pyc | CurImagePlugin.cpython-313.pyc | Other | 2,479 | 0.8 | 0 | 0 | node-utils | 95 | 2024-06-24T11:00:19.374218 | MIT | false | 6f2abdef00a1de694685f9951c71e6cf |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\DcxImagePlugin.cpython-313.pyc | DcxImagePlugin.cpython-313.pyc | Other | 3,030 | 0.8 | 0 | 0 | node-utils | 174 | 2025-04-13T20:19:59.156711 | Apache-2.0 | false | 187452322a7009992cdbd7b21a203216 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\DdsImagePlugin.cpython-313.pyc | DdsImagePlugin.cpython-313.pyc | Other | 24,941 | 0.8 | 0.009756 | 0.020725 | vue-tools | 382 | 2025-05-24T01:14:15.164812 | Apache-2.0 | false | a865668b4a1b756551061c9b0e70f59e |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\EpsImagePlugin.cpython-313.pyc | EpsImagePlugin.cpython-313.pyc | Other | 16,237 | 0.95 | 0.015707 | 0.016129 | awesome-app | 544 | 2024-07-26T06:28:13.063885 | GPL-3.0 | false | 781e2dec6f0d373506139f7c144fc7ac |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\ExifTags.cpython-313.pyc | ExifTags.cpython-313.pyc | Other | 11,742 | 0.8 | 0.011628 | 0 | awesome-app | 168 | 2025-06-01T12:38:14.528764 | MIT | false | 0bdef75bc6e8463319df160822332de1 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\features.cpython-313.pyc | features.cpython-313.pyc | Other | 14,112 | 0.95 | 0.171233 | 0 | node-utils | 220 | 2023-12-17T15:12:08.584616 | GPL-3.0 | false | 2a022523d0715759bfc4ee5b436a8ac8 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\FitsImagePlugin.cpython-313.pyc | FitsImagePlugin.cpython-313.pyc | Other | 6,254 | 0.8 | 0 | 0 | vue-tools | 558 | 2024-03-14T20:04:16.379740 | MIT | false | 6b729f8c4a64d9a14d5a4183d6b9b37b |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\FliImagePlugin.cpython-313.pyc | FliImagePlugin.cpython-313.pyc | Other | 7,160 | 0.8 | 0 | 0 | node-utils | 145 | 2024-07-11T01:52:57.272860 | MIT | false | 03b82d112aacb31341207d27ee58d8f2 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\FontFile.cpython-313.pyc | FontFile.cpython-313.pyc | Other | 4,590 | 0.95 | 0.045455 | 0 | react-lib | 389 | 2025-04-18T20:22:37.337036 | MIT | false | ac9137d0f51eb1cb4ca7134502149a9b |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\FpxImagePlugin.cpython-313.pyc | FpxImagePlugin.cpython-313.pyc | Other | 7,909 | 0.8 | 0 | 0 | awesome-app | 61 | 2024-11-15T17:44:31.732897 | BSD-3-Clause | false | ec0c46487dc97bc9f556d6f1f9a074a2 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\FtexImagePlugin.cpython-313.pyc | FtexImagePlugin.cpython-313.pyc | Other | 5,432 | 0.8 | 0.058824 | 0.089888 | node-utils | 978 | 2025-02-15T06:09:32.292772 | BSD-3-Clause | false | c14bdea970e13d0420ea1b049aac87ad |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GbrImagePlugin.cpython-313.pyc | GbrImagePlugin.cpython-313.pyc | Other | 3,805 | 0.8 | 0 | 0 | awesome-app | 36 | 2024-04-25T00:28:49.629064 | Apache-2.0 | false | 98bdbdbe1e63399dea5f0b744777489a |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GdImageFile.cpython-313.pyc | GdImageFile.cpython-313.pyc | Other | 3,467 | 0.95 | 0.129032 | 0 | node-utils | 814 | 2024-08-20T06:19:02.439741 | GPL-3.0 | false | 14d95ee915dbfbc8ac256429c0852929 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GifImagePlugin.cpython-313.pyc | GifImagePlugin.cpython-313.pyc | Other | 46,664 | 0.95 | 0.022026 | 0.004728 | react-lib | 850 | 2024-10-27T13:39:11.142099 | Apache-2.0 | false | d1ca23ea8d09fc3fe4a268d99379b09b |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GimpGradientFile.cpython-313.pyc | GimpGradientFile.cpython-313.pyc | Other | 5,539 | 0.8 | 0.031746 | 0 | react-lib | 124 | 2024-06-26T04:56:30.923172 | GPL-3.0 | false | 2fe9dae6d7fdc5e3d49766529fc379a5 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GimpPaletteFile.cpython-313.pyc | GimpPaletteFile.cpython-313.pyc | Other | 2,863 | 0.8 | 0.034483 | 0 | python-kit | 375 | 2024-01-18T17:59:01.159532 | GPL-3.0 | false | beb4482c8fa6966703c93e501482ef7d |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\GribStubImagePlugin.cpython-313.pyc | GribStubImagePlugin.cpython-313.pyc | Other | 2,793 | 0.8 | 0 | 0 | react-lib | 275 | 2023-10-13T03:38:17.287123 | Apache-2.0 | false | 376b71ba85fe6cafc5b76ebc4cd2b45c |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\Hdf5StubImagePlugin.cpython-313.pyc | Hdf5StubImagePlugin.cpython-313.pyc | Other | 2,758 | 0.8 | 0 | 0 | node-utils | 457 | 2024-01-15T00:10:03.578040 | GPL-3.0 | false | 2652dd63485d17e938e5a2463f37a872 |
\n\n | .venv\Lib\site-packages\PIL\__pycache__\IcnsImagePlugin.cpython-313.pyc | IcnsImagePlugin.cpython-313.pyc | Other | 17,491 | 0.8 | 0.008584 | 0.018182 | react-lib | 115 | 2024-09-04T13:17:31.398801 | MIT | false | 22a2a9dc4273d6d6bad91d0cc366dff4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.