From 176bd71a47fe2a434782dcc3119d0fc0a4593db9 Mon Sep 17 00:00:00 2001 From: Guillaume Ayoub Date: Thu, 22 Aug 2024 23:14:35 +0200 Subject: [PATCH] Store original and PDF stream images in different cache slots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- weasyprint/images.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/weasyprint/images.py b/weasyprint/images.py index 0dd1bb24f..51e4f67a9 100644 --- a/weasyprint/images.py +++ b/weasyprint/images.py @@ -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): @@ -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', @@ -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):