Skip to content

Commit

Permalink
Store original and PDF stream images in different cache slots
Browse files Browse the repository at this point in the history
We used to replace the original image by the PDF stream image in cache after
the first PDF rendering. It’s broken because the PDF stream image is not a
valid image, and can’t be opened by Pillow if it has to be rendered twice.

Replacing the original image with the final one was probably supposed to save
some time and/or some memory, but my quick tests show no performance problem
with this commit.

Fix #1942, fix #2228.
  • Loading branch information
liZe committed Aug 22, 2024
1 parent 6ebb4f4 commit 176bd71
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions weasyprint/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ def draw(self, stream, concrete_width, concrete_height, image_rendering):
concrete_width, 0, 0, -concrete_height, 0, concrete_height)
stream.draw_x_object(image_name)

def cache_image_data(self, data, filename=None, alpha=False):
def cache_image_data(self, data, filename=None, slot='source'):
if filename:
return LazyLocalImage(filename)
else:
key = f'{self.id}{int(alpha)}{self._dpi or ""}'
key = f'{self.id}-{slot}-{self._dpi or ""}'
return LazyImage(self._cache, key, data)

def get_x_object(self, interpolate, dpi_ratio):
Expand Down Expand Up @@ -183,7 +183,7 @@ def get_x_object(self, interpolate, dpi_ratio):
png_data = self._get_png_data(pillow_image)
# Save alpha channel as mask
alpha_data = self._get_png_data(alpha)
stream = self.cache_image_data(alpha_data, alpha=True)
stream = self.cache_image_data(alpha_data, slot='streamalpha')
extra['SMask'] = pydyf.Stream([stream], extra={
'Filter': '/FlateDecode',
'Type': '/XObject',
Expand All @@ -202,7 +202,7 @@ def get_x_object(self, interpolate, dpi_ratio):
png_data = self._get_png_data(
Image.open(io.BytesIO(self.image_data.data)))

return pydyf.Stream([self.cache_image_data(png_data)], extra)
return pydyf.Stream([self.cache_image_data(png_data, slot='stream')], extra)

@staticmethod
def _get_png_data(pillow_image):
Expand Down

0 comments on commit 176bd71

Please sign in to comment.