Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/PcxImagePlugin.py: 64%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

96 statements  

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 

29__lazy_modules__ = {"PIL._binary", "io"} 

30 

31import io 

32import logging 

33 

34from . import Image, ImageFile, ImagePalette 

35from ._binary import i16le as i16 

36from ._binary import o8 

37from ._binary import o16le as o16 

38 

39TYPE_CHECKING = False 

40if TYPE_CHECKING: 

41 from typing import IO 

42 

43logger = logging.getLogger(__name__) 

44 

45 

46def _accept(prefix: bytes) -> bool: 

47 return len(prefix) >= 2 and prefix[0] == 10 and prefix[1] in [0, 2, 3, 5] 

48 

49 

50## 

51# Image plugin for Paintbrush images. 

52 

53 

54class PcxImageFile(ImageFile.ImageFile): 

55 format = "PCX" 

56 format_description = "Paintbrush" 

57 

58 def _open(self) -> None: 

59 # header 

60 assert self.fp is not None 

61 

62 s = self.fp.read(68) 

63 if not _accept(s): 

64 msg = "not a PCX file" 

65 raise SyntaxError(msg) 

66 

67 # image 

68 bbox = i16(s, 4), i16(s, 6), i16(s, 8) + 1, i16(s, 10) + 1 

69 if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: 

70 msg = "bad PCX image size" 

71 raise SyntaxError(msg) 

72 logger.debug("BBox: %s %s %s %s", *bbox) 

73 

74 offset = self.fp.tell() + 60 

75 

76 # format 

77 version = s[1] 

78 bits = s[3] 

79 planes = s[65] 

80 provided_stride = i16(s, 66) 

81 logger.debug( 

82 "PCX version %s, bits %s, planes %s, stride %s", 

83 version, 

84 bits, 

85 planes, 

86 provided_stride, 

87 ) 

88 

89 self.info["dpi"] = i16(s, 12), i16(s, 14) 

90 

91 if bits == 1 and planes == 1: 

92 mode = rawmode = "1" 

93 

94 elif bits == 1 and planes in (2, 4): 

95 mode = "P" 

96 rawmode = f"P;{planes}L" 

97 self.palette = ImagePalette.raw("RGB", s[16:64]) 

98 

99 elif version == 5 and bits == 8 and planes == 1: 

100 mode = rawmode = "L" 

101 # FIXME: hey, this doesn't work with the incremental loader !!! 

102 self.fp.seek(-769, io.SEEK_END) 

103 s = self.fp.read(769) 

104 if len(s) == 769 and s[0] == 12: 

105 # check if the palette is linear grayscale 

106 for i in range(256): 

107 if s[i * 3 + 1 : i * 3 + 4] != o8(i) * 3: 

108 mode = rawmode = "P" 

109 break 

110 if mode == "P": 

111 self.palette = ImagePalette.raw("RGB", s[1:]) 

112 

113 elif version == 5 and bits == 8 and planes == 3: 

114 mode = "RGB" 

115 rawmode = "RGB;L" 

116 

117 else: 

118 msg = "unknown PCX mode" 

119 raise OSError(msg) 

120 

121 self._mode = mode 

122 self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] 

123 

124 # Don't trust the passed in stride. 

125 # Calculate the approximate position for ourselves. 

126 # CVE-2020-35653 

127 stride = (self._size[0] * bits + 7) // 8 

128 

129 # While the specification states that this must be even, 

130 # not all images follow this 

131 if provided_stride != stride: 

132 stride += stride % 2 

133 

134 logger.debug("size: %sx%s", *self.size) 

135 

136 self.tile = [ImageFile._Tile("pcx", None, offset, (rawmode, planes * stride))] 

137 

138 

139# -------------------------------------------------------------------- 

140# save PCX files 

141 

142 

143SAVE = { 

144 # mode: (version, bits, planes, raw mode) 

145 "1": (2, 1, 1, "1"), 

146 "L": (5, 8, 1, "L"), 

147 "P": (5, 8, 1, "P"), 

148 "RGB": (5, 8, 3, "RGB;L"), 

149} 

150 

151 

152def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: 

153 if im.width == 0 or im.height == 0: 

154 msg = "Cannot write empty image as PCX" 

155 raise ValueError(msg) 

156 

157 try: 

158 version, bits, planes, rawmode = SAVE[im.mode] 

159 except KeyError as e: 

160 msg = f"Cannot save {im.mode} images as PCX" 

161 raise ValueError(msg) from e 

162 

163 # bytes per plane 

164 stride = (im.size[0] * bits + 7) // 8 

165 # stride should be even 

166 stride += stride % 2 

167 # Stride needs to be kept in sync with the PcxEncode.c version. 

168 # Ideally it should be passed in in the state, but the bytes value 

169 # gets overwritten. 

170 

171 logger.debug( 

172 "PcxImagePlugin._save: xwidth: %d, bits: %d, stride: %d", 

173 im.size[0], 

174 bits, 

175 stride, 

176 ) 

177 

178 # under windows, we could determine the current screen size with 

179 # "Image.core.display_mode()[1]", but I think that's overkill... 

180 

181 screen = im.size 

182 

183 dpi = 100, 100 

184 

185 # PCX header 

186 fp.write( 

187 o8(10) 

188 + o8(version) 

189 + o8(1) 

190 + o8(bits) 

191 + o16(0) 

192 + o16(0) 

193 + o16(im.size[0] - 1) 

194 + o16(im.size[1] - 1) 

195 + o16(dpi[0]) 

196 + o16(dpi[1]) 

197 + b"\0" * 24 

198 + b"\xff" * 24 

199 + b"\0" 

200 + o8(planes) 

201 + o16(stride) 

202 + o16(1) 

203 + o16(screen[0]) 

204 + o16(screen[1]) 

205 + b"\0" * 54 

206 ) 

207 

208 assert fp.tell() == 128 

209 

210 ImageFile._save(im, fp, [ImageFile._Tile("pcx", args=(rawmode, bits * planes))]) 

211 

212 if im.mode == "P": 

213 # colour palette 

214 fp.write(o8(12)) 

215 palette = im.im.getpalette("RGB") 

216 palette += b"\x00" * (768 - len(palette)) 

217 fp.write(palette) # 768 bytes 

218 elif im.mode == "L": 

219 # grayscale palette 

220 fp.write(o8(12)) 

221 for i in range(256): 

222 fp.write(o8(i) * 3) 

223 

224 

225# -------------------------------------------------------------------- 

226# registry 

227 

228 

229Image.register_open(PcxImageFile.format, PcxImageFile, _accept) 

230Image.register_save(PcxImageFile.format, _save) 

231 

232Image.register_extension(PcxImageFile.format, ".pcx") 

233 

234Image.register_mime(PcxImageFile.format, "image/x-pcx")