Skip to content

Commit

Permalink
Support interlaced PNGs (closes #274)
Browse files Browse the repository at this point in the history
- deinterlace PNG files on the fly
- warn the user that this can slow down rendering

Deinterlacing is very slow for large images. For a 3840x2160 RBA PNG,
this takes almost 10 seconds. This could possibly be sped up a lot
by similar techniques (struct unpacking) as used in the PNGReader
methods.
  • Loading branch information
brechtm committed Aug 27, 2021
1 parent 8be80dd commit 2fcc882
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 9 deletions.
4 changes: 3 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ New Features:
in the source document instead of as footnotes. This is controlled by the
*location* style property for notes. (issue #269, PR #271 by Alex Fargus)
* The *before* and *after* style properties are now supported on paragraphs too
* The separator string between an inline admonition title and the adminition
* The separator string between an inline admonition title and the admonition
text is now specified in the style sheet (*after* property of the *admonition
inline title* style), so it can be overridden (default: space character).
* Warn about targets in ``rinoh_targets`` that are not defined in
Expand All @@ -19,6 +19,8 @@ New Features:
and downwards.
* Admonition: selectors for the first paragraph where the admonition title was
prepended to (e.g. *note title paragraph*).
* Support interlaced PNG images (#274). Note that this can slow down rendering
significantly for many/large interlaced images.

Changed:

Expand Down
35 changes: 27 additions & 8 deletions src/rinoh/backend/pdf/xobject/png.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.

from io import BytesIO
from itertools import islice
from itertools import islice, chain
from pathlib import Path
from struct import Struct, pack

from . import purepng

from ..cos import Array, Integer, Stream, Name, Dictionary, Real
from ..filter import FlateDecode, FlateDecodeParams
from ....warnings import warn

from . import (XObjectImage, DEVICE_GRAY, DEVICE_RGB, INDEXED, PERCEPTUAL,
ABSOLUTE_COLORIMETRIC, RELATIVE_COLORIMETRIC, SATURATION)
Expand All @@ -32,9 +33,6 @@ def __init__(self, file_or_filename):
png.preamble()
except purepng.FormatError as format_error:
raise ValueError(*format_error.args)
assert png.compression == 0
assert png.filter == 0
assert png.interlace == 0
color_params = FlateDecodeParams(predictor=10, colors=png.color_planes,
bits_per_component=png.bitdepth,
columns=png.width)
Expand All @@ -43,18 +41,39 @@ def __init__(self, file_or_filename):
filter=FlateDecode(color_params))
if png.rendering_intent is not None:
self['Intent'] = RENDERING_INTENT[png.rendering_intent]
idat_decomp = png.idatdecomp()
if png.interlace == 1:
if isinstance(file_or_filename, Path):
warn(f"WARNING: Deinterlacing '{file_or_filename}' for "
"embedding into PDF; this can significantly slow down "
"rendering.")
iraw = bytearray(chain(*idat_decomp))
raw = png.deinterlace(iraw)
bytes_per_row = png.width * png.planes
rows = (raw[i*bytes_per_row:(i+1)*bytes_per_row]
for i in range(png.height))
writer = purepng.Writer(png.width, png.height,
alpha=png.alpha, bitdepth=png.bitdepth,
greyscale=png.greyscale,
palette=png.palette() if png.plte else None,
transparent=png.transparent,
compression=png.compression,
interlace=False)
idat_decomp = writer.idat(rows)
if png.alpha: # grayscale/RGB with alpha channel
smask_params = FlateDecodeParams(predictor=10, colors=1,
bits_per_component=png.bitdepth,
columns=png.width)
self['SMask'] = XObjectImage(png.width, png.height, DEVICE_GRAY,
png.bitdepth,
filter=FlateDecode(smask_params))
for color_row, alpha_row in self._split_color_alpha(png):
for color_row, alpha_row in self._split_color_alpha(png, idat_decomp):
self.write(color_row, bypass_predictor=True)
self['SMask'].write(alpha_row, bypass_predictor=True)
else:
for idat_chunk in png.idat():
idat = (writer.comp_idat(idat_decomp) if png.interlace
else png.idat())
for idat_chunk in idat:
self.write_raw(idat_chunk)
if png.trns:
if png.plte: # alpha values assigned to palette colors
Expand Down Expand Up @@ -137,11 +156,11 @@ def _icc_profile(self, png):
else:
return None

def _split_color_alpha(self, png):
def _split_color_alpha(self, png, idat_decomp):
bytedepth = png.bitdepth // 8
num_color_bytes = png.color_planes * bytedepth
idat = BytesIO()
for idat_chunk in png.idatdecomp():
for idat_chunk in idat_decomp:
idat.write(idat_chunk)
row_num_bytes = 1 + (png.color_planes + 1) * bytedepth * png.width
pixel_color_fmt = '{}B{}x'.format(num_color_bytes, bytedepth)
Expand Down

0 comments on commit 2fcc882

Please sign in to comment.