__  __    __   __  _____      _            _          _____ _          _ _ 
 |  \/  |   \ \ / / |  __ \    (_)          | |        / ____| |        | | |
 | \  / |_ __\ V /  | |__) | __ ___   ____ _| |_ ___  | (___ | |__   ___| | |
 | |\/| | '__|> <   |  ___/ '__| \ \ / / _` | __/ _ \  \___ \| '_ \ / _ \ | |
 | |  | | |_ / . \  | |   | |  | |\ V / (_| | ||  __/  ____) | | | |  __/ | |
 |_|  |_|_(_)_/ \_\ |_|   |_|  |_| \_/ \__,_|\__\___| |_____/|_| |_|\___V 2.1
 if you need WebShell for Seo everyday contact me on Telegram
 Telegram Address : @jackleet
        
        
For_More_Tools: Telegram: @jackleet | Bulk Smtp support mail sender | Business Mail Collector | Mail Bouncer All Mail | Bulk Office Mail Validator | Html Letter private



Upload:

Command:

[email protected]: ~ $
#
# The Python Imaging Library.
# $Id$
#
# image palette object
#
# History:
# 1996-03-11 fl   Rewritten.
# 1997-01-03 fl   Up and running.
# 1997-08-23 fl   Added load hack
# 2001-04-16 fl   Fixed randint shadow bug in random()
#
# Copyright (c) 1997-2001 by Secret Labs AB
# Copyright (c) 1996-1997 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from __future__ import annotations

import array
from collections.abc import Sequence
from typing import IO, TYPE_CHECKING

from . import GimpGradientFile, GimpPaletteFile, ImageColor, PaletteFile

if TYPE_CHECKING:
    from . import Image


class ImagePalette:
    """
    Color palette for palette mapped images

    :param mode: The mode to use for the palette. See:
        :ref:`concept-modes`. Defaults to "RGB"
    :param palette: An optional palette. If given, it must be a bytearray,
        an array or a list of ints between 0-255. The list must consist of
        all channels for one color followed by the next color (e.g. RGBRGBRGB).
        Defaults to an empty palette.
    """

    def __init__(
        self,
        mode: str = "RGB",
        palette: Sequence[int] | bytes | bytearray | None = None,
    ) -> None:
        self.mode = mode
        self.rawmode: str | None = None  # if set, palette contains raw data
        self.palette = palette or bytearray()
        self.dirty: int | None = None

    @property
    def palette(self) -> Sequence[int] | bytes | bytearray:
        return self._palette

    @palette.setter
    def palette(self, palette: Sequence[int] | bytes | bytearray) -> None:
        self._colors: dict[tuple[int, ...], int] | None = None
        self._palette = palette

    @property
    def colors(self) -> dict[tuple[int, ...], int]:
        if self._colors is None:
            mode_len = len(self.mode)
            self._colors = {}
            for i in range(0, len(self.palette), mode_len):
                color = tuple(self.palette[i : i + mode_len])
                if color in self._colors:
                    continue
                self._colors[color] = i // mode_len
        return self._colors

    @colors.setter
    def colors(self, colors: dict[tuple[int, ...], int]) -> None:
        self._colors = colors

    def copy(self) -> ImagePalette:
        new = ImagePalette()

        new.mode = self.mode
        new.rawmode = self.rawmode
        if self.palette is not None:
            new.palette = self.palette[:]
        new.dirty = self.dirty

        return new

    def getdata(self) -> tuple[str, Sequence[int] | bytes | bytearray]:
        """
        Get palette contents in format suitable for the low-level
        ``im.putpalette`` primitive.

        .. warning:: This method is experimental.
        """
        if self.rawmode:
            return self.rawmode, self.palette
        return self.mode, self.tobytes()

    def tobytes(self) -> bytes:
        """Convert palette to bytes.

        .. warning:: This method is experimental.
        """
        if self.rawmode:
            msg = "palette contains raw palette data"
            raise ValueError(msg)
        if isinstance(self.palette, bytes):
            return self.palette
        arr = array.array("B", self.palette)
        return arr.tobytes()

    # Declare tostring as an alias for tobytes
    tostring = tobytes

    def _new_color_index(
        self, image: Image.Image | None = None, e: Exception | None = None
    ) -> int:
        if not isinstance(self.palette, bytearray):
            self._palette = bytearray(self.palette)
        index = len(self.palette) // 3
        special_colors: tuple[int | tuple[int, ...] | None, ...] = ()
        if image:
            special_colors = (
                image.info.get("background"),
                image.info.get("transparency"),
            )
            while index in special_colors:
                index += 1
        if index >= 256:
            if image:
                # Search for an unused index
                for i, count in reversed(list(enumerate(image.histogram()))):
                    if count == 0 and i not in special_colors:
                        index = i
                        break
            if index >= 256:
                msg = "cannot allocate more than 256 colors"
                raise ValueError(msg) from e
        return index

    def getcolor(
        self,
        color: tuple[int, ...],
        image: Image.Image | None = None,
    ) -> int:
        """Given an rgb tuple, allocate palette entry.

        .. warning:: This method is experimental.
        """
        if self.rawmode:
            msg = "palette contains raw palette data"
            raise ValueError(msg)
        if isinstance(color, tuple):
            if self.mode == "RGB":
                if len(color) == 4:
                    if color[3] != 255:
                        msg = "cannot add non-opaque RGBA color to RGB palette"
                        raise ValueError(msg)
                    color = color[:3]
            elif self.mode == "RGBA":
                if len(color) == 3:
                    color += (255,)
            try:
                return self.colors[color]
            except KeyError as e:
                # allocate new color slot
                index = self._new_color_index(image, e)
                assert isinstance(self._palette, bytearray)
                self.colors[color] = index
                if index * 3 < len(self.palette):
                    self._palette = (
                        self._palette[: index * 3]
                        + bytes(color)
                        + self._palette[index * 3 + 3 :]
                    )
                else:
                    self._palette += bytes(color)
                self.dirty = 1
                return index
        else:
            msg = f"unknown color specifier: {repr(color)}"  # type: ignore[unreachable]
            raise ValueError(msg)

    def save(self, fp: str | IO[str]) -> None:
        """Save palette to text file.

        .. warning:: This method is experimental.
        """
        if self.rawmode:
            msg = "palette contains raw palette data"
            raise ValueError(msg)
        if isinstance(fp, str):
            fp = open(fp, "w")
        fp.write("# Palette\n")
        fp.write(f"# Mode: {self.mode}\n")
        for i in range(256):
            fp.write(f"{i}")
            for j in range(i * len(self.mode), (i + 1) * len(self.mode)):
                try:
                    fp.write(f" {self.palette[j]}")
                except IndexError:
                    fp.write(" 0")
            fp.write("\n")
        fp.close()


# --------------------------------------------------------------------
# Internal


def raw(rawmode: str, data: Sequence[int] | bytes | bytearray) -> ImagePalette:
    palette = ImagePalette()
    palette.rawmode = rawmode
    palette.palette = data
    palette.dirty = 1
    return palette


# --------------------------------------------------------------------
# Factories


def make_linear_lut(black: int, white: float) -> list[int]:
    if black == 0:
        return [int(white * i // 255) for i in range(256)]

    msg = "unavailable when black is non-zero"
    raise NotImplementedError(msg)  # FIXME


def make_gamma_lut(exp: float) -> list[int]:
    return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]


def negative(mode: str = "RGB") -> ImagePalette:
    palette = list(range(256 * len(mode)))
    palette.reverse()
    return ImagePalette(mode, [i // len(mode) for i in palette])


def random(mode: str = "RGB") -> ImagePalette:
    from random import randint

    palette = [randint(0, 255) for _ in range(256 * len(mode))]
    return ImagePalette(mode, palette)


def sepia(white: str = "#fff0c0") -> ImagePalette:
    bands = [make_linear_lut(0, band) for band in ImageColor.getrgb(white)]
    return ImagePalette("RGB", [bands[i % 3][i // 3] for i in range(256 * 3)])


def wedge(mode: str = "RGB") -> ImagePalette:
    palette = list(range(256 * len(mode)))
    return ImagePalette(mode, [i // len(mode) for i in palette])


def load(filename: str) -> tuple[bytes, str]:
    # FIXME: supports GIMP gradients only

    with open(filename, "rb") as fp:
        paletteHandlers: list[
            type[
                GimpPaletteFile.GimpPaletteFile
                | GimpGradientFile.GimpGradientFile
                | PaletteFile.PaletteFile
            ]
        ] = [
            GimpPaletteFile.GimpPaletteFile,
            GimpGradientFile.GimpGradientFile,
            PaletteFile.PaletteFile,
        ]
        for paletteHandler in paletteHandlers:
            try:
                fp.seek(0)
                lut = paletteHandler(fp).getpalette()
                if lut:
                    break
            except (SyntaxError, ValueError):
                pass
        else:
            msg = "cannot load palette"
            raise OSError(msg)

    return lut  # data, rawmode

Filemanager

Name Type Size Permission Actions
__pycache__ Folder 0755
BdfFontFile.py File 3.4 KB 0644
BlpImagePlugin.py File 16.29 KB 0644
BmpImagePlugin.py File 19.29 KB 0644
BufrStubImagePlugin.py File 1.71 KB 0644
ContainerIO.py File 4.5 KB 0644
CurImagePlugin.py File 1.75 KB 0644
DcxImagePlugin.py File 1.99 KB 0644
DdsImagePlugin.py File 16.54 KB 0644
EpsImagePlugin.py File 15.98 KB 0644
ExifTags.py File 9.7 KB 0644
FitsImagePlugin.py File 4.53 KB 0644
FliImagePlugin.py File 4.57 KB 0644
FontFile.py File 3.49 KB 0644
FpxImagePlugin.py File 7.12 KB 0644
FtexImagePlugin.py File 3.44 KB 0644
GbrImagePlugin.py File 2.94 KB 0644
GdImageFile.py File 2.74 KB 0644
GifImagePlugin.py File 40.48 KB 0644
GimpGradientFile.py File 3.81 KB 0644
GimpPaletteFile.py File 1.39 KB 0644
GribStubImagePlugin.py File 1.71 KB 0644
Hdf5StubImagePlugin.py File 1.71 KB 0644
IcnsImagePlugin.py File 12.65 KB 0644
IcoImagePlugin.py File 12.18 KB 0644
ImImagePlugin.py File 11.17 KB 0644
Image.py File 142.7 KB 0644
ImageChops.py File 7.76 KB 0644
ImageCms.py File 41.03 KB 0644
ImageColor.py File 9.22 KB 0644
ImageDraw.py File 41.28 KB 0644
ImageDraw2.py File 7.06 KB 0644
ImageEnhance.py File 3.54 KB 0644
ImageFile.py File 25.51 KB 0644
ImageFilter.py File 18.27 KB 0644
ImageFont.py File 62.75 KB 0644
ImageGrab.py File 5.86 KB 0644
ImageMath.py File 11.66 KB 0644
ImageMode.py File 2.62 KB 0644
ImageMorph.py File 8.36 KB 0644
ImageOps.py File 24.5 KB 0644
ImagePalette.py File 8.79 KB 0644
ImagePath.py File 371 B 0644
ImageQt.py File 6.67 KB 0644
ImageSequence.py File 2.15 KB 0644
ImageShow.py File 9.76 KB 0644
ImageStat.py File 5.2 KB 0644
ImageTransform.py File 3.79 KB 0644
ImageWin.py File 7.9 KB 0644
ImtImagePlugin.py File 2.6 KB 0644
IptcImagePlugin.py File 6.51 KB 0644
Jpeg2KImagePlugin.py File 13.56 KB 0644
JpegImagePlugin.py File 31.05 KB 0644
JpegPresets.py File 12.09 KB 0644
McIdasImagePlugin.py File 1.89 KB 0644
MicImagePlugin.py File 2.62 KB 0644
MpegImagePlugin.py File 2.05 KB 0644
MpoImagePlugin.py File 6.07 KB 0644
MspImagePlugin.py File 5.74 KB 0644
PSDraw.py File 6.75 KB 0644
PaletteFile.py File 1.18 KB 0644
PalmImagePlugin.py File 9.13 KB 0644
PcdImagePlugin.py File 1.55 KB 0644
PcfFontFile.py File 6.98 KB 0644
PcxImagePlugin.py File 6.1 KB 0644
PdfImagePlugin.py File 9.13 KB 0644
PdfParser.py File 37.09 KB 0644
PixarImagePlugin.py File 1.71 KB 0644
PngImagePlugin.py File 49.67 KB 0644
PpmImagePlugin.py File 12.06 KB 0644
PsdImagePlugin.py File 8.42 KB 0644
QoiImagePlugin.py File 4.08 KB 0644
SgiImagePlugin.py File 6.57 KB 0644
SpiderImagePlugin.py File 9.9 KB 0644
SunImagePlugin.py File 4.48 KB 0644
TarIO.py File 1.34 KB 0644
TgaImagePlugin.py File 6.82 KB 0644
TiffImagePlugin.py File 81.44 KB 0644
TiffTags.py File 16.68 KB 0644
WalImageFile.py File 5.57 KB 0644
WebPImagePlugin.py File 9.83 KB 0644
WmfImagePlugin.py File 5.02 KB 0644
XVThumbImagePlugin.py File 2.06 KB 0644
XbmImagePlugin.py File 2.6 KB 0644
XpmImagePlugin.py File 3.15 KB 0644
__init__.py File 1.96 KB 0644
__main__.py File 133 B 0644
_binary.py File 2.49 KB 0644
_deprecate.py File 1.89 KB 0644
_imaging.cpython-313-x86_64-linux-gnu.so File 750.65 KB 0644
_imaging.pyi File 868 B 0644
_imagingcms.cpython-313-x86_64-linux-gnu.so File 41.73 KB 0644
_imagingcms.pyi File 4.29 KB 0644
_imagingft.cpython-313-x86_64-linux-gnu.so File 45.63 KB 0644
_imagingft.pyi File 1.75 KB 0644
_imagingmath.cpython-313-x86_64-linux-gnu.so File 34.48 KB 0644
_imagingmath.pyi File 63 B 0644
_imagingmorph.cpython-313-x86_64-linux-gnu.so File 14.48 KB 0644
_imagingmorph.pyi File 63 B 0644
_imagingtk.pyi File 63 B 0644
_tkinter_finder.py File 540 B 0644
_typing.py File 1.21 KB 0644
_util.py File 635 B 0644
_version.py File 87 B 0644
_webp.cpython-313-x86_64-linux-gnu.so File 23.97 KB 0644
_webp.pyi File 63 B 0644
features.py File 11 KB 0644
py.typed File 0 B 0644
report.py File 100 B 0644
Filemanager