Skip to content

Commit f6e1361

Browse files
authored
Merge pull request #3441 from trailofbits/perf/lazy-pil-import
perf: lazy import PIL in nes.py and jpeg.py
2 parents 3311444 + 9d6c04d commit f6e1361

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

polyfile/jpeg.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,16 @@
44
from .fileutils import FileStream, Tempfile
55
from .polyfile import Match, register_parser, Submatch
66

7-
from PIL import Image
7+
8+
def _get_pil_image():
9+
"""Lazy import PIL.Image only when needed (for JPEG2000 parsing)."""
10+
from PIL import Image
11+
return Image
812

913

1014
@register_parser("image/jp2")
1115
def parse_jpeg2000(file_stream: FileStream, parent: Match):
16+
Image = _get_pil_image()
1217
with Tempfile(file_stream.read(parent.length)) as input_bytes:
1318
img = Image.open(input_bytes)
1419
with BytesIO() as img_data:

polyfile/nes.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
import base64
22
from io import BytesIO
3-
4-
from PIL import Image, ImageDraw
3+
from typing import TYPE_CHECKING
54

65
from .polyfile import register_parser, InvalidMatch, Submatch
76

7+
if TYPE_CHECKING:
8+
from PIL import Image as PILImage
9+
10+
11+
def _get_pil():
12+
"""Lazy import PIL only when needed (for NES ROM CHR bank rendering)."""
13+
from PIL import Image, ImageDraw
14+
return Image, ImageDraw
15+
816

917
def parse_ines_header(header, parent=None):
1018
magic = header[:4]
@@ -130,7 +138,8 @@ def chr_values(chr_bytes: bytes):
130138
((((chr_bytes[offset + y + 8] >> shift) & 0b1)) << 1) | ((chr_bytes[offset + y] >> shift) & 0b1)
131139

132140

133-
def render_chr(chr_bytes: bytes) -> Image:
141+
def render_chr(chr_bytes: bytes) -> "PILImage":
142+
Image, ImageDraw = _get_pil()
134143
img = Image.new(mode='L', size=(8*16, 8*32))
135144
d = ImageDraw.Draw(img)
136145
for x, y, pixel in chr_values(chr_bytes):

0 commit comments

Comments
 (0)