Skip to content

fix(pdfcanvas): embed large opaque raster images as JPEG, not raw samples - #457

Open
tannevaled wants to merge 3 commits into
mainfrom
worktree-agent-a59fa07cd82f3e336
Open

tannevaled wants to merge 3 commits into
mainfrom
worktree-agent-a59fa07cd82f3e336

Conversation

@tannevaled

Copy link
Copy Markdown
Contributor

Summary

Fixes the mechanism behind a go-slides report of a 7-9x PDF/PPTX size blowup
when switching a slide theme from Marp's ![bg] to a CSS
background: linear-gradient(...), url(...) center/cover no-repeat rule.

CSS background-image and <img>/![bg] are not divergent paths in
this engine: paint/vector.go's bgBitmap (background tiles) and its
image case (<img> elements) both terminate in the same
v.c.Image(src, r) call. The real cause is in pdfcanvas.Canvas.Image
itself: every raster image, regardless of how it reached the canvas, went
through pdfkit's default DrawImage, which embeds the raw decoded RGB
samples under /FlateDecode. Flate recovers only zlib's ~2-3x on
photographic content, where the source photo's own JPEG encoding typically
got 10-20x — accounting for the measured blowup. go-gfx/gfx's
raster.Image carries no record of its original encoding by the time it
reaches the canvas, so the source bytes can't be reused; re-encoding is the
available fix. pdfkit already exposes a DrawJPEG (/DCTDecode) path that
pdfcanvas simply never called.

Fix

pdfcanvas/pdfcanvas.go: Canvas.Image now re-encodes an image as a JPEG
(quality 90) via pdfkit's DrawJPEG when it is both opaque (DrawJPEG has
no soft mask, so any transparency keeps the existing lossless path) and at
or above 200x200px (below that, JPEG's fixed overhead and block artifacts
are a worse trade than the lossless default, e.g. small icons/logos). A
JPEG encode error falls back to the lossless default rather than losing the
image.

Testing

pdfcanvas/jpegphoto_test.go (new):

  • TestLargeOpaqueImageIsEmbeddedAsJPEG: a synthetic photo-like opaque
    image is embedded under /DCTDecode, well under half the size of
    pdfkit's own /FlateDecode default for the same pixels.
  • TestTransparentLargeImageStaysLossless, TestSmallOpaqueImageStaysLossless:
    the two guard conditions keep the lossless path.
  • TestCSSBackgroundImagePhotoIsJPEGCompressed: end-to-end repro through
    the real engine+paint pipeline from a CSS background: url(...) center / cover no-repeat rule (not a Marp ![bg]), proving the two are not
    divergent paths.
  • TestJpegPhotoFallsBackOnEncodeError, TestIsOpaqueScansFallbackPixels,
    TestIsOpaqueTrustsOpaqueFastPathOverPixels: close out mutsweep's own
    gap report on the new guards (encode-error fallback, the per-pixel scan's
    alpha boundary, and the Opaque() fast path actually being trusted
    rather than recomputed).

Full gate green: gotest ./..., gofmt -l . (clean for touched files),
go vet ./..., govulncheck ./.... A pre-existing, unrelated -race
flake in engine/js (TestWorkerCloneUnsupportedValueFromWorkerLogged,
TestWorkerWasmInstanceofAndPerformanceNow) was confirmed to reproduce
identically on HEAD without this change (stash-isolated before/after).

Out of scope

The PPTX-side blowup go-slides also measured is not an engine/officecanvas
defect: officecanvas.Canvas.Image only records a Shape{Kind: KindImage, Image: img}; it does not itself encode PPTX media parts. go-slides'
consumer code should check its own PPTX media-part writer for the same
naive full-resolution encode of Shape.Image.

🤖 Generated with Claude Code

tannevaled and others added 3 commits November 29, 2026 18:47
…ples

pdfcanvas.Canvas.Image always took pdfkit's default path (raw decoded RGB
samples under /FlateDecode), even for a photographic source: zlib recovers
only ~2-3x on that kind of noise, where the source's own JPEG compression
typically got 10-20x, producing a 4x-9x blowup on export (go-slides saw a
4.4 MB deck become 35.8 MB). This affects a CSS background-image and an
<img> identically — both reach paint.Canvas.Image the same way — so it was
never a code-path divergence, just a missing fast path.

pdfkit already exposes DrawJPEG (DCTDecode, no re-encoding) but nothing
called it. A large (>=200x200) fully opaque image is now re-encoded as
JPEG at quality 90 and embedded through DrawJPEG; anything with
transparency, or smaller than that, keeps the lossless path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
handlayout-waiver: go-webengine/engine is a browser rendering engine, not
a go-widgets GUI application. The three flagged sites in the preceding
commit are not application layout: `b.Dx()*b.Dy()` is a pixel-count
threshold deciding whether an image is large enough to re-encode as JPEG,
and the `for y; for x` loop is isOpaque's per-pixel alpha scan (the
fallback for an image.Image that has no Opaque() fast path). Both are
PDF/image-encoding arithmetic, pdfcanvas's own domain, with no
VBox/HBox/Grid/Splitter equivalent to delegate to.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
mutsweep flagged 3 of the 5 new guards as unswept (err!=nil on the JPEG
encode call, the Opaque() fast path's own "ok", and the fallback scan's
per-pixel alpha test). Add targeted fixtures for each:

- hugeOpaqueImage: 1-pixel-tall, 1<<16-wide bounds, real opaque pixels,
  cheap to scan but large enough to trip image/jpeg's own size limit —
  exercises jpegPhoto's encode-error fallback.
- scanProbe: no Opaque() method, so isOpaque must take the per-pixel
  fallback; one variant is uniformly opaque, one has a single pixel at
  alpha 254, pinning the scan's own boundary.
- opaqueLies: implements Opaque() reporting a fixed answer that disagrees
  with its (always actually opaque) pixels, so asserting isOpaque's return
  value proves the fast path's answer was trusted rather than recomputed
  from pixels — an assertion, not a panic, per mutsweep's own guidance that
  a panic-only kill is luck, not a test.

Re-ran mutsweep -only on all 5 lines: 5 caught, 0 survived, 0 panic-only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant