1#
2# The Python Imaging Library.
3# $Id$
4#
5# PCX file handling
6#
7# This format was originally used by ZSoft's popular PaintBrush
8# program for the IBM PC. It is also supported by many MS-DOS and
9# Windows applications, including the Windows PaintBrush program in
10# Windows 3.
11#
12# history:
13# 1995-09-01 fl Created
14# 1996-05-20 fl Fixed RGB support
15# 1997-01-03 fl Fixed 2-bit and 4-bit support
16# 1999-02-03 fl Fixed 8-bit support (broken in 1.0b1)
17# 1999-02-07 fl Added write support
18# 2002-06-09 fl Made 2-bit and 4-bit support a bit more robust
19# 2002-07-30 fl Seek from to current position, not beginning of file
20# 2003-06-03 fl Extract DPI settings (info["dpi"])
21#
22# Copyright (c) 1997-2003 by Secret Labs AB.
23# Copyright (c) 1995-2003 by Fredrik Lundh.
24#
25# See the README file for information on usage and redistribution.
26#
27from __future__ import annotations
28
29import io
30import logging
31from typing import IO
32
33from . import Image, ImageFile, ImagePalette
34from ._binary import i16le as i16
35from ._binary import o8
36from ._binary import o16le as o16
37
38logger = logging.getLogger(__name__)
39
40
41def _accept(prefix: bytes) -> bool:
42 return prefix[0] == 10 and prefix[1] in [0, 2, 3, 5]
43
44
45##
46# Image plugin for Paintbrush images.
47
48
49class PcxImageFile(ImageFile.ImageFile):
50 format = "PCX"
51 format_description = "Paintbrush"
52
53 def _open(self) -> None:
54 # header
55 assert self.fp is not None
56
57 s = self.fp.read(128)
58 if not _accept(s):
59 msg = "not a PCX file"
60 raise SyntaxError(msg)
61
62 # image
63 bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1
64 if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:
65 msg = "bad PCX image size"
66 raise SyntaxError(msg)
67 logger.debug("BBox: %s %s %s %s", *bbox)
68
69 # format
70 version = s[1]
71 bits = s[3]
72 planes = s[65]
73 provided_stride = i16(s, 66)
74 logger.debug(
75 "PCX version %s, bits %s, planes %s, stride %s",
76 version,
77 bits,
78 planes,
79 provided_stride,
80 )
81
82 self.info["dpi"] = i16(s, 12), i16(s, 14)
83
84 if bits == 1 and planes == 1:
85 mode = rawmode = "1"
86
87 elif bits == 1 and planes in (2, 4):
88 mode = "P"
89 rawmode = "P;%dL" % planes
90 self.palette = ImagePalette.raw("RGB", s[16:64])
91
92 elif version == 5 and bits == 8 and planes == 1:
93 mode = rawmode = "L"
94 # FIXME: hey, this doesn't work with the incremental loader !!!
95 self.fp.seek(-769, io.SEEK_END)
96 s = self.fp.read(769)
97 if len(s) == 769 and s[0] == 12:
98 # check if the palette is linear grayscale
99 for i in range(256):
100 if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3:
101 mode = rawmode = "P"
102 break
103 if mode == "P":
104 self.palette = ImagePalette.raw("RGB", s[1:])
105 self.fp.seek(128)
106
107 elif version == 5 and bits == 8 and planes == 3:
108 mode = "RGB"
109 rawmode = "RGB;L"
110
111 else:
112 msg = "unknown PCX mode"
113 raise OSError(msg)
114
115 self._mode = mode
116 self._size = bbox[2] - bbox[0], bbox[3] - bbox[1]
117
118 # Don't trust the passed in stride.
119 # Calculate the approximate position for ourselves.
120 # CVE-2020-35653
121 stride = (self._size[0] * bits + 7) // 8
122
123 # While the specification states that this must be even,
124 # not all images follow this
125 if provided_stride != stride:
126 stride += stride % 2
127
128 bbox = (0, 0) + self.size
129 logger.debug("size: %sx%s", *self.size)
130
131 self.tile = [
132 ImageFile._Tile("pcx", bbox, self.fp.tell(), (rawmode, planes * stride))
133 ]
134
135
136# --------------------------------------------------------------------
137# save PCX files
138
139
140SAVE = {
141 # mode: (version, bits, planes, raw mode)
142 "1": (2, 1, 1, "1"),
143 "L": (5, 8, 1, "L"),
144 "P": (5, 8, 1, "P"),
145 "RGB": (5, 8, 3, "RGB;L"),
146}
147
148
149def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
150 try:
151 version, bits, planes, rawmode = SAVE[im.mode]
152 except KeyError as e:
153 msg = f"Cannot save {im.mode} images as PCX"
154 raise ValueError(msg) from e
155
156 # bytes per plane
157 stride = (im.size[0] * bits + 7) // 8
158 # stride should be even
159 stride += stride % 2
160 # Stride needs to be kept in sync with the PcxEncode.c version.
161 # Ideally it should be passed in in the state, but the bytes value
162 # gets overwritten.
163
164 logger.debug(
165 "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d",
166 im.size[0],
167 bits,
168 stride,
169 )
170
171 # under windows, we could determine the current screen size with
172 # "Image.core.display_mode()[1]", but I think that's overkill...
173
174 screen = im.size
175
176 dpi = 100, 100
177
178 # PCX header
179 fp.write(
180 o8(10)
181 + o8(version)
182 + o8(1)
183 + o8(bits)
184 + o16(0)
185 + o16(0)
186 + o16(im.size[0] - 1)
187 + o16(im.size[1] - 1)
188 + o16(dpi[0])
189 + o16(dpi[1])
190 + b"\0" * 24
191 + b"\xFF" * 24
192 + b"\0"
193 + o8(planes)
194 + o16(stride)
195 + o16(1)
196 + o16(screen[0])
197 + o16(screen[1])
198 + b"\0" * 54
199 )
200
201 assert fp.tell() == 128
202
203 ImageFile._save(
204 im, fp, [ImageFile._Tile("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))]
205 )
206
207 if im.mode == "P":
208 # colour palette
209 fp.write(o8(12))
210 palette = im.im.getpalette("RGB", "RGB")
211 palette += b"\x00" * (768 - len(palette))
212 fp.write(palette) # 768 bytes
213 elif im.mode == "L":
214 # grayscale palette
215 fp.write(o8(12))
216 for i in range(256):
217 fp.write(o8(i) * 3)
218
219
220# --------------------------------------------------------------------
221# registry
222
223
224Image.register_open(PcxImageFile.format, PcxImageFile, _accept)
225Image.register_save(PcxImageFile.format, _save)
226
227Image.register_extension(PcxImageFile.format, ".pcx")
228
229Image.register_mime(PcxImageFile.format, "image/x-pcx")