Aluode/PerceptionLabPortable
0
1#
2# The Python Imaging Library.
3# $Id$
4#
5# GD file handling
6#
7# History:
8# 1996-04-12 fl Created
9#
10# Copyright (c) 1997 by Secret Labs AB.
11# Copyright (c) 1996 by Fredrik Lundh.
12#
13# See the README file for information on usage and redistribution.
14#
15
16
17"""
18.. note::
19 This format cannot be automatically recognized, so the
20 class is not registered for use with :py:func:`PIL.Image.open()`. To open a
21 gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
22
23.. warning::
24 THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
25 implementation is provided for convenience and demonstrational
26 purposes only.
27"""
28from __future__ import annotations
29
30from typing import IO
31
32from . import ImageFile, ImagePalette, UnidentifiedImageError
33from ._binary import i16be as i16
34from ._binary import i32be as i32
35from ._typing import StrOrBytesPath
36
37
38class GdImageFile(ImageFile.ImageFile):
39 """
40 Image plugin for the GD uncompressed format. Note that this format
41 is not supported by the standard :py:func:`PIL.Image.open()` function. To use
42 this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
43 use the :py:func:`PIL.GdImageFile.open()` function.
44 """
45
46 format = "GD"
47 format_description = "GD uncompressed images"
48
49 def _open(self) -> None:
50 # Header
51 assert self.fp is not None
52
53 s = self.fp.read(1037)
54
55 if i16(s) not in [65534, 65535]:
56 msg = "Not a valid GD 2.x .gd file"
57 raise SyntaxError(msg)
58
59 self._mode = "P"
60 self._size = i16(s, 2), i16(s, 4)
61
62 true_color = s[6]
63 true_color_offset = 2 if true_color else 0
64
65 # transparency index
66 tindex = i32(s, 7 + true_color_offset)
67 if tindex < 256:
68 self.info["transparency"] = tindex
69
70 self.palette = ImagePalette.raw(
71 "RGBX", s[7 + true_color_offset + 6 : 7 + true_color_offset + 6 + 256 * 4]
72 )
73
74 self.tile = [
75 ImageFile._Tile(
76 "raw",
77 (0, 0) + self.size,
78 7 + true_color_offset + 6 + 256 * 4,
79 "L",
80 )
81 ]
82
83
84def open(fp: StrOrBytesPath | IO[bytes], mode: str = "r") -> GdImageFile:
85 """
86 Load texture from a GD image file.
87
88 :param fp: GD file name, or an opened file handle.
89 :param mode: Optional mode. In this version, if the mode argument
90 is given, it must be "r".
91 :returns: An image instance.
92 :raises OSError: If the image could not be read.
93 """
94 if mode != "r":
95 msg = "bad mode"
96 raise ValueError(msg)
97
98 try:
99 return GdImageFile(fp)
100 except SyntaxError as e:
101 msg = "cannot identify this image file"
102 raise UnidentifiedImageError(msg) from e
103 