Replace slice and comparison with startswith

This commit is contained in:
Hugo van Kemenade 2025-02-15 19:28:43 +02:00
parent fa58313c41
commit 1e574e6f8b
43 changed files with 72 additions and 73 deletions

View File

@ -77,8 +77,8 @@ def test_app(test_file: str) -> None:
with Image.open(test_file) as im: with Image.open(test_file) as im:
assert im.applist[0][0] == "APP1" assert im.applist[0][0] == "APP1"
assert im.applist[1][0] == "APP2" assert im.applist[1][0] == "APP2"
assert ( assert im.applist[1][1].startswith(
im.applist[1][1][:16] == b"MPF\x00MM\x00*\x00\x00\x00\x08\x00\x03\xb0\x00" b"MPF\x00MM\x00*\x00\x00\x00\x08\x00\x03\xb0\x00"
) )
assert len(im.applist) == 2 assert len(im.applist) == 2

View File

@ -40,7 +40,7 @@ def test_read_exif_metadata() -> None:
def test_read_exif_metadata_without_prefix() -> None: def test_read_exif_metadata_without_prefix() -> None:
with Image.open("Tests/images/flower2.webp") as im: with Image.open("Tests/images/flower2.webp") as im:
# Assert prefix is not present # Assert prefix is not present
assert im.info["exif"][:6] != b"Exif\x00\x00" assert not im.info["exif"].startswith(b"Exif\x00\x00")
exif = im.getexif() exif = im.getexif()
assert exif[305] == "Adobe Photoshop CS6 (Macintosh)" assert exif[305] == "Adobe Photoshop CS6 (Macintosh)"

View File

@ -74,12 +74,12 @@ class TestImage:
def test_sanity(self) -> None: def test_sanity(self) -> None:
im = Image.new("L", (100, 100)) im = Image.new("L", (100, 100))
assert repr(im)[:45] == "<PIL.Image.Image image mode=L size=100x100 at" assert repr(im).startswith("<PIL.Image.Image image mode=L size=100x100 at")
assert im.mode == "L" assert im.mode == "L"
assert im.size == (100, 100) assert im.size == (100, 100)
im = Image.new("RGB", (100, 100)) im = Image.new("RGB", (100, 100))
assert repr(im)[:45] == "<PIL.Image.Image image mode=RGB size=100x100 " assert repr(im).startswith("<PIL.Image.Image image mode=RGB size=100x100 ")
assert im.mode == "RGB" assert im.mode == "RGB"
assert im.size == (100, 100) assert im.size == (100, 100)

View File

@ -285,7 +285,7 @@ Image.register_decoder("DXT5", DXT5Decoder)
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"DDS " return prefix.startswith(b"DDS ")
Image.register_open(DdsImageFile.format, DdsImageFile, _accept) Image.register_open(DdsImageFile.format, DdsImageFile, _accept)

View File

@ -54,7 +54,7 @@ true color.
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"SPAM" return prefix.startswith(b"SPAM")
class SpamImageFile(ImageFile.ImageFile): class SpamImageFile(ImageFile.ImageFile):

View File

@ -43,7 +43,7 @@ def bdf_char(
s = f.readline() s = f.readline()
if not s: if not s:
return None return None
if s[:9] == b"STARTCHAR": if s.startswith(b"STARTCHAR"):
break break
id = s[9:].strip().decode("ascii") id = s[9:].strip().decode("ascii")
@ -51,7 +51,7 @@ def bdf_char(
props = {} props = {}
while True: while True:
s = f.readline() s = f.readline()
if not s or s[:6] == b"BITMAP": if not s or s.startswith(b"BITMAP"):
break break
i = s.find(b" ") i = s.find(b" ")
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")
@ -60,7 +60,7 @@ def bdf_char(
bitmap = bytearray() bitmap = bytearray()
while True: while True:
s = f.readline() s = f.readline()
if not s or s[:7] == b"ENDCHAR": if not s or s.startswith(b"ENDCHAR"):
break break
bitmap += s[:-1] bitmap += s[:-1]
@ -96,7 +96,7 @@ class BdfFontFile(FontFile.FontFile):
super().__init__() super().__init__()
s = fp.readline() s = fp.readline()
if s[:13] != b"STARTFONT 2.1": if not s.startswith(b"STARTFONT 2.1"):
msg = "not a valid BDF file" msg = "not a valid BDF file"
raise SyntaxError(msg) raise SyntaxError(msg)
@ -105,7 +105,7 @@ class BdfFontFile(FontFile.FontFile):
while True: while True:
s = fp.readline() s = fp.readline()
if not s or s[:13] == b"ENDPROPERTIES": if not s or s.startswith(b"ENDPROPERTIES"):
break break
i = s.find(b" ") i = s.find(b" ")
props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii") props[s[:i].decode("ascii")] = s[i + 1 : -1].decode("ascii")

View File

@ -246,7 +246,7 @@ class BLPFormatError(NotImplementedError):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] in (b"BLP1", b"BLP2") return prefix.startswith((b"BLP1", b"BLP2"))
class BlpImageFile(ImageFile.ImageFile): class BlpImageFile(ImageFile.ImageFile):

View File

@ -50,7 +50,7 @@ BIT2MODE = {
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:2] == b"BM" return prefix.startswith(b"BM")
def _dib_accept(prefix: bytes) -> bool: def _dib_accept(prefix: bytes) -> bool:

View File

@ -33,7 +33,7 @@ def register_handler(handler: ImageFile.StubHandler | None) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"BUFR" or prefix[:4] == b"ZCZC" return prefix.startswith((b"BUFR", b"ZCZC"))
class BufrStubImageFile(ImageFile.StubImageFile): class BufrStubImageFile(ImageFile.StubImageFile):

View File

@ -26,7 +26,7 @@ from ._binary import i32le as i32
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"\0\0\2\0" return prefix.startswith(b"\0\0\2\0")
## ##

View File

@ -564,7 +564,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"DDS " return prefix.startswith(b"DDS ")
Image.register_open(DdsImageFile.format, DdsImageFile, _accept) Image.register_open(DdsImageFile.format, DdsImageFile, _accept)

View File

@ -170,7 +170,9 @@ def Ghostscript(
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"%!PS" or (len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5) return prefix.startswith(b"%!PS") or (
len(prefix) >= 4 and i32(prefix) == 0xC6D3D0C5
)
## ##
@ -295,7 +297,7 @@ class EpsImageFile(ImageFile.ImageFile):
m = field.match(s) m = field.match(s)
if m: if m:
k = m.group(1) k = m.group(1)
if k[:8] == "PS-Adobe": if k.startswith("PS-Adobe"):
self.info["PS-Adobe"] = k[9:] self.info["PS-Adobe"] = k[9:]
else: else:
self.info[k] = "" self.info[k] = ""

View File

@ -17,7 +17,7 @@ from . import Image, ImageFile
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:6] == b"SIMPLE" return prefix.startswith(b"SIMPLE")
class FitsImageFile(ImageFile.ImageFile): class FitsImageFile(ImageFile.ImageFile):

View File

@ -42,7 +42,7 @@ MODES = {
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:8] == olefile.MAGIC return prefix.startswith(olefile.MAGIC)
## ##

View File

@ -108,7 +108,7 @@ class FtexImageFile(ImageFile.ImageFile):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == MAGIC return prefix.startswith(MAGIC)
Image.register_open(FtexImageFile.format, FtexImageFile, _accept) Image.register_open(FtexImageFile.format, FtexImageFile, _accept)

View File

@ -67,7 +67,7 @@ LOADING_STRATEGY = LoadingStrategy.RGB_AFTER_FIRST
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:6] in [b"GIF87a", b"GIF89a"] return prefix.startswith((b"GIF87a", b"GIF89a"))
## ##
@ -257,7 +257,7 @@ class GifImageFile(ImageFile.ImageFile):
# application extension # application extension
# #
info["extension"] = block, self.fp.tell() info["extension"] = block, self.fp.tell()
if block[:11] == b"NETSCAPE2.0": if block.startswith(b"NETSCAPE2.0"):
block = self.data() block = self.data()
if block and len(block) >= 3 and block[0] == 1: if block and len(block) >= 3 and block[0] == 1:
self.info["loop"] = i16(block, 1) self.info["loop"] = i16(block, 1)

View File

@ -116,7 +116,7 @@ class GimpGradientFile(GradientFile):
"""File handler for GIMP's gradient format.""" """File handler for GIMP's gradient format."""
def __init__(self, fp: IO[bytes]) -> None: def __init__(self, fp: IO[bytes]) -> None:
if fp.readline()[:13] != b"GIMP Gradient": if not fp.readline().startswith(b"GIMP Gradient"):
msg = "not a GIMP gradient file" msg = "not a GIMP gradient file"
raise SyntaxError(msg) raise SyntaxError(msg)

View File

@ -29,7 +29,7 @@ class GimpPaletteFile:
def __init__(self, fp: IO[bytes]) -> None: def __init__(self, fp: IO[bytes]) -> None:
palette = [o8(i) * 3 for i in range(256)] palette = [o8(i) * 3 for i in range(256)]
if fp.readline()[:12] != b"GIMP Palette": if not fp.readline().startswith(b"GIMP Palette"):
msg = "not a GIMP palette file" msg = "not a GIMP palette file"
raise SyntaxError(msg) raise SyntaxError(msg)

View File

@ -33,7 +33,7 @@ def register_handler(handler: ImageFile.StubHandler | None) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"GRIB" and prefix[7] == 1 return prefix.startswith(b"GRIB") and prefix[7] == 1
class GribStubImageFile(ImageFile.StubImageFile): class GribStubImageFile(ImageFile.StubImageFile):

View File

@ -33,7 +33,7 @@ def register_handler(handler: ImageFile.StubHandler | None) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:8] == b"\x89HDF\r\n\x1a\n" return prefix.startswith(b"\x89HDF\r\n\x1a\n")
class HDF5StubImageFile(ImageFile.StubImageFile): class HDF5StubImageFile(ImageFile.StubImageFile):

View File

@ -117,14 +117,14 @@ def read_png_or_jpeg2000(
sig = fobj.read(12) sig = fobj.read(12)
im: Image.Image im: Image.Image
if sig[:8] == b"\x89PNG\x0d\x0a\x1a\x0a": if sig.startswith(b"\x89PNG\x0d\x0a\x1a\x0a"):
fobj.seek(start) fobj.seek(start)
im = PngImagePlugin.PngImageFile(fobj) im = PngImagePlugin.PngImageFile(fobj)
Image._decompression_bomb_check(im.size) Image._decompression_bomb_check(im.size)
return {"RGBA": im} return {"RGBA": im}
elif ( elif (
sig[:4] == b"\xff\x4f\xff\x51" sig.startswith(b"\xff\x4f\xff\x51")
or sig[:4] == b"\x0d\x0a\x87\x0a" or sig.startswith(b"\x0d\x0a\x87\x0a")
or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" or sig == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
): ):
if not enable_jpeg2k: if not enable_jpeg2k:
@ -387,7 +387,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == MAGIC return prefix.startswith(MAGIC)
Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept) Image.register_open(IcnsImageFile.format, IcnsImageFile, _accept)

View File

@ -118,7 +118,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == _MAGIC return prefix.startswith(_MAGIC)
class IconHeader(NamedTuple): class IconHeader(NamedTuple):

View File

@ -209,7 +209,7 @@ class ImImageFile(ImageFile.ImageFile):
self._mode = self.info[MODE] self._mode = self.info[MODE]
# Skip forward to start of image data # Skip forward to start of image data
while s and s[:1] != b"\x1a": while s and not s.startswith(b"\x1a"):
s = self.fp.read(1) s = self.fp.read(1)
if not s: if not s:
msg = "File truncated" msg = "File truncated"
@ -247,7 +247,7 @@ class ImImageFile(ImageFile.ImageFile):
self._fp = self.fp # FIXME: hack self._fp = self.fp # FIXME: hack
if self.rawmode[:2] == "F;": if self.rawmode.startswith("F;"):
# ifunc95 formats # ifunc95 formats
try: try:
# use bit decoder (if necessary) # use bit decoder (if necessary)

View File

@ -3998,7 +3998,7 @@ class Exif(_ExifBase):
if tag == ExifTags.IFD.MakerNote: if tag == ExifTags.IFD.MakerNote:
from .TiffImagePlugin import ImageFileDirectory_v2 from .TiffImagePlugin import ImageFileDirectory_v2
if tag_data[:8] == b"FUJIFILM": if tag_data.startswith(b"FUJIFILM"):
ifd_offset = i32le(tag_data, 8) ifd_offset = i32le(tag_data, 8)
ifd_data = tag_data[ifd_offset:] ifd_data = tag_data[ifd_offset:]

View File

@ -352,9 +352,8 @@ class Jpeg2KImageFile(ImageFile.ImageFile):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return ( return prefix.startswith(
prefix[:4] == b"\xff\x4f\xff\x51" (b"\xff\x4f\xff\x51", b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a")
or prefix[:12] == b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a"
) )

View File

@ -77,7 +77,7 @@ def APP(self: JpegImageFile, marker: int) -> None:
self.app[app] = s # compatibility self.app[app] = s # compatibility
self.applist.append((app, s)) self.applist.append((app, s))
if marker == 0xFFE0 and s[:4] == b"JFIF": if marker == 0xFFE0 and s.startswith(b"JFIF"):
# extract JFIF information # extract JFIF information
self.info["jfif"] = version = i16(s, 5) # version self.info["jfif"] = version = i16(s, 5) # version
self.info["jfif_version"] = divmod(version, 256) self.info["jfif_version"] = divmod(version, 256)
@ -95,19 +95,19 @@ def APP(self: JpegImageFile, marker: int) -> None:
self.info["dpi"] = tuple(d * 2.54 for d in jfif_density) self.info["dpi"] = tuple(d * 2.54 for d in jfif_density)
self.info["jfif_unit"] = jfif_unit self.info["jfif_unit"] = jfif_unit
self.info["jfif_density"] = jfif_density self.info["jfif_density"] = jfif_density
elif marker == 0xFFE1 and s[:6] == b"Exif\0\0": elif marker == 0xFFE1 and s.startswith(b"Exif\0\0"):
# extract EXIF information # extract EXIF information
if "exif" in self.info: if "exif" in self.info:
self.info["exif"] += s[6:] self.info["exif"] += s[6:]
else: else:
self.info["exif"] = s self.info["exif"] = s
self._exif_offset = self.fp.tell() - n + 6 self._exif_offset = self.fp.tell() - n + 6
elif marker == 0xFFE1 and s[:29] == b"http://ns.adobe.com/xap/1.0/\x00": elif marker == 0xFFE1 and s.startswith(b"http://ns.adobe.com/xap/1.0/\x00"):
self.info["xmp"] = s.split(b"\x00", 1)[1] self.info["xmp"] = s.split(b"\x00", 1)[1]
elif marker == 0xFFE2 and s[:5] == b"FPXR\0": elif marker == 0xFFE2 and s.startswith(b"FPXR\0"):
# extract FlashPix information (incomplete) # extract FlashPix information (incomplete)
self.info["flashpix"] = s # FIXME: value will change self.info["flashpix"] = s # FIXME: value will change
elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0": elif marker == 0xFFE2 and s.startswith(b"ICC_PROFILE\0"):
# Since an ICC profile can be larger than the maximum size of # Since an ICC profile can be larger than the maximum size of
# a JPEG marker (64K), we need provisions to split it into # a JPEG marker (64K), we need provisions to split it into
# multiple markers. The format defined by the ICC specifies # multiple markers. The format defined by the ICC specifies
@ -120,7 +120,7 @@ def APP(self: JpegImageFile, marker: int) -> None:
# reassemble the profile, rather than assuming that the APP2 # reassemble the profile, rather than assuming that the APP2
# markers appear in the correct sequence. # markers appear in the correct sequence.
self.icclist.append(s) self.icclist.append(s)
elif marker == 0xFFED and s[:14] == b"Photoshop 3.0\x00": elif marker == 0xFFED and s.startswith(b"Photoshop 3.0\x00"):
# parse the image resource block # parse the image resource block
offset = 14 offset = 14
photoshop = self.info.setdefault("photoshop", {}) photoshop = self.info.setdefault("photoshop", {})
@ -153,7 +153,7 @@ def APP(self: JpegImageFile, marker: int) -> None:
except struct.error: except struct.error:
break # insufficient data break # insufficient data
elif marker == 0xFFEE and s[:5] == b"Adobe": elif marker == 0xFFEE and s.startswith(b"Adobe"):
self.info["adobe"] = i16(s, 5) self.info["adobe"] = i16(s, 5)
# extract Adobe custom properties # extract Adobe custom properties
try: try:
@ -162,7 +162,7 @@ def APP(self: JpegImageFile, marker: int) -> None:
pass pass
else: else:
self.info["adobe_transform"] = adobe_transform self.info["adobe_transform"] = adobe_transform
elif marker == 0xFFE2 and s[:4] == b"MPF\0": elif marker == 0xFFE2 and s.startswith(b"MPF\0"):
# extract MPO information # extract MPO information
self.info["mp"] = s[4:] self.info["mp"] = s[4:]
# offset is current location minus buffer size # offset is current location minus buffer size
@ -325,7 +325,7 @@ MARKER = {
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
# Magic number was taken from https://en.wikipedia.org/wiki/JPEG # Magic number was taken from https://en.wikipedia.org/wiki/JPEG
return prefix[:3] == b"\xff\xd8\xff" return prefix.startswith(b"\xff\xd8\xff")
## ##
@ -547,7 +547,7 @@ def _getmp(self: JpegImageFile) -> dict[int, Any] | None:
return None return None
file_contents = io.BytesIO(data) file_contents = io.BytesIO(data)
head = file_contents.read(8) head = file_contents.read(8)
endianness = ">" if head[:4] == b"\x4d\x4d\x00\x2a" else "<" endianness = ">" if head.startswith(b"\x4d\x4d\x00\x2a") else "<"
# process dictionary # process dictionary
from . import TiffImagePlugin from . import TiffImagePlugin

View File

@ -23,7 +23,7 @@ from . import Image, ImageFile
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:8] == b"\x00\x00\x00\x00\x00\x00\x00\x04" return prefix.startswith(b"\x00\x00\x00\x00\x00\x00\x00\x04")
## ##

View File

@ -26,7 +26,7 @@ from . import Image, TiffImagePlugin
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:8] == olefile.MAGIC return prefix.startswith(olefile.MAGIC)
## ##

View File

@ -54,7 +54,7 @@ class BitStream:
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"\x00\x00\x01\xb3" return prefix.startswith(b"\x00\x00\x01\xb3")
## ##

View File

@ -37,7 +37,7 @@ from ._binary import o16le as o16
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] in [b"DanM", b"LinS"] return prefix.startswith((b"DanM", b"LinS"))
## ##
@ -69,7 +69,7 @@ class MspImageFile(ImageFile.ImageFile):
self._mode = "1" self._mode = "1"
self._size = i16(s, 4), i16(s, 6) self._size = i16(s, 4), i16(s, 6)
if s[:4] == b"DanM": if s.startswith(b"DanM"):
self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")] self.tile = [ImageFile._Tile("raw", (0, 0) + self.size, 32, "1")]
else: else:
self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)] self.tile = [ImageFile._Tile("MSP", (0, 0) + self.size, 32)]

View File

@ -32,7 +32,7 @@ class PaletteFile:
if not s: if not s:
break break
if s[:1] == b"#": if s.startswith(b"#"):
continue continue
if len(s) > 100: if len(s) > 100:
msg = "bad palette file" msg = "bad palette file"

View File

@ -34,7 +34,7 @@ class PcdImageFile(ImageFile.ImageFile):
self.fp.seek(2048) self.fp.seek(2048)
s = self.fp.read(2048) s = self.fp.read(2048)
if s[:4] != b"PCD_": if not s.startswith(b"PCD_"):
msg = "not a PCD file" msg = "not a PCD file"
raise SyntaxError(msg) raise SyntaxError(msg)

View File

@ -28,7 +28,7 @@ from ._binary import i16le as i16
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"\200\350\000\000" return prefix.startswith(b"\200\350\000\000")
## ##

View File

@ -740,7 +740,7 @@ class PngStream(ChunkStream):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:8] == _MAGIC return prefix.startswith(_MAGIC)
## ##

View File

@ -47,7 +47,7 @@ MODES = {
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[0:1] == b"P" and prefix[1] in b"0123456fy" return prefix.startswith(b"P") and prefix[1] in b"0123456fy"
## ##

View File

@ -47,7 +47,7 @@ MODES = {
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"8BPS" return prefix.startswith(b"8BPS")
## ##

View File

@ -14,7 +14,7 @@ from ._binary import i32be as i32
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] == b"qoif" return prefix.startswith(b"qoif")
class QoiImageFile(ImageFile.ImageFile): class QoiImageFile(ImageFile.ImageFile):

View File

@ -288,7 +288,7 @@ if not getattr(Image.core, "libtiff_support_custom_tags", True):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:4] in PREFIXES return prefix.startswith(tuple(PREFIXES))
def _limit_rational( def _limit_rational(
@ -1280,7 +1280,7 @@ class TiffImageFile(ImageFile.ImageFile):
blocks = {} blocks = {}
val = self.tag_v2.get(ExifTags.Base.ImageResources) val = self.tag_v2.get(ExifTags.Base.ImageResources)
if val: if val:
while val[:4] == b"8BIM": while val.startswith(b"8BIM"):
id = i16(val[4:6]) id = i16(val[4:6])
n = math.ceil((val[6] + 1) / 2) * 2 n = math.ceil((val[6] + 1) / 2) * 2
size = i32(val[6 + n : 10 + n]) size = i32(val[6 + n : 10 + n])

View File

@ -21,7 +21,7 @@ _VP8_MODES_BY_IDENTIFIER = {
def _accept(prefix: bytes) -> bool | str: def _accept(prefix: bytes) -> bool | str:
is_riff_file_format = prefix[:4] == b"RIFF" is_riff_file_format = prefix.startswith(b"RIFF")
is_webp_file = prefix[8:12] == b"WEBP" is_webp_file = prefix[8:12] == b"WEBP"
is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER is_valid_vp8_mode = prefix[12:16] in _VP8_MODES_BY_IDENTIFIER

View File

@ -68,9 +68,7 @@ if hasattr(Image.core, "drawwmf"):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return ( return prefix.startswith((b"\xd7\xcd\xc6\x9a\x00\x00", b"\x01\x00\x00\x00"))
prefix[:6] == b"\xd7\xcd\xc6\x9a\x00\x00" or prefix[:4] == b"\x01\x00\x00\x00"
)
## ##
@ -87,7 +85,7 @@ class WmfStubImageFile(ImageFile.StubImageFile):
# check placable header # check placable header
s = self.fp.read(80) s = self.fp.read(80)
if s[:6] == b"\xd7\xcd\xc6\x9a\x00\x00": if s.startswith(b"\xd7\xcd\xc6\x9a\x00\x00"):
# placeable windows metafile # placeable windows metafile
# get units per inch # get units per inch
@ -116,7 +114,7 @@ class WmfStubImageFile(ImageFile.StubImageFile):
msg = "Unsupported WMF file format" msg = "Unsupported WMF file format"
raise SyntaxError(msg) raise SyntaxError(msg)
elif s[:4] == b"\x01\x00\x00\x00" and s[40:44] == b" EMF": elif s.startswith(b"\x01\x00\x00\x00") and s[40:44] == b" EMF":
# enhanced metafile # enhanced metafile
# get bounding box # get bounding box

View File

@ -34,7 +34,7 @@ for r in range(8):
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:6] == _MAGIC return prefix.startswith(_MAGIC)
## ##

View File

@ -38,7 +38,7 @@ xbm_head = re.compile(
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix.lstrip()[:7] == b"#define" return prefix.lstrip().startswith(b"#define")
## ##

View File

@ -25,7 +25,7 @@ xpm_head = re.compile(b'"([0-9]*) ([0-9]*) ([0-9]*) ([0-9]*)')
def _accept(prefix: bytes) -> bool: def _accept(prefix: bytes) -> bool:
return prefix[:9] == b"/* XPM */" return prefix.startswith(b"/* XPM */")
## ##
@ -81,7 +81,7 @@ class XpmImageFile(ImageFile.ImageFile):
rgb = s[i + 1] rgb = s[i + 1]
if rgb == b"None": if rgb == b"None":
self.info["transparency"] = c self.info["transparency"] = c
elif rgb[:1] == b"#": elif rgb.startswith(b"#"):
# FIXME: handle colour names (see ImagePalette.py) # FIXME: handle colour names (see ImagePalette.py)
rgb = int(rgb[1:], 16) rgb = int(rgb[1:], 16)
palette[c] = ( palette[c] = (