Skip to content

Rasterize SVG into Image with FreeType - #7652

Open
Grantim wants to merge 16 commits into
masterfrom
svg-rasterize-image
Open

Grantim wants to merge 16 commits into
masterfrom
svg-rasterize-image

Conversation

@Grantim

@Grantim Grantim commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

ImageLoad::fromSvg( file | data, resolution ) rasterizes the shapes that LinesLoad::fromSvg reads, fitting the view box uniformly in the center: solid fill and stroke (hex, rgb(), black, white, currentColor) with opacity, fill rule, stroke width, caps, joins, miter limit and dashes, group and element opacity, display: none, and use of elements in the document. Anything that would otherwise give a silently wrong image returns an error instead: other paints, drawn image/switch/foreignObject/nested svg, text with content, use of symbol, use cycles and references outside the document, nesting deeper than 128 levels or more than 100000 drawn elements, strokes under non-uniform scale or skew, units other than px, style sheets, mask, filter, markers, blend modes, pathLength of dashed strokes, non-default preserveAspectRatio, out-of-range coordinates and a resolution out of 1..32767; clip-path and visibility are ignored. Curves are flattened into 32 segments each, so the function is meant for small images like icons.

FreeType's outline renderer and stroker do the anti-aliased scan conversion, so MRIOExtras now links FreeType (already used by MRSymbolMesh) next to tinyxml2. This is meant for ribbon icons that have no PNG of the needed size.

Five commits fix the shared SVG parser, which LinesLoad::fromSvg also uses: compact arc flags (a9 9 0 11-18 0), NaN from near-semicircle and degenerate arcs, smooth curves after the other curve kind (S after Q, T after C), Debug asserts on arcs at large coordinates, crashes on shapes without d/points, errors on empty ones, and rects now start at (x+rx, y) going +x as their SVG path does, which reverses the point order of sharp rects.

  • MRTest SVG cases pass in Release and Debug on Windows; full Release suite passes
  • CI on all platforms

Generated with Claude Code

Grantim and others added 2 commits December 1, 2026 19:02
ImageLoad::fromSvg draws the shapes of LinesLoad::fromSvg with solid fill and stroke, fill rules and group opacity, fitting the view box into the given resolution. FreeType's outline renderer and stroker do the scan conversion, so MRIOExtras links FreeType together with tinyxml2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Skipping them silently gave wrong images, e.g. blank shapes drawn through use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Grantim
Grantim marked this pull request as draft December 1, 2026 15:07
Grantim and others added 12 commits December 1, 2026 19:48
…metry

Rounding made the squared center offset of such arcs slightly negative, which gave NaN points (an assert in Debug); path, polygon and polyline without d or points dereferenced a null attribute and now are empty shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ported SVG

Stroked contours are deduplicated in 26.6 points, so a subpath collapsed into one point draws its caps instead of crashing FreeType, and circles are closed with a join instead of two caps. Style sheets, mask, filter, stroke-dasharray, switch and nested svg give errors; a is drawn as a group, display none hides an element, currentColor is black.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Arc flags are parsed as single characters, so compact arcs like "a9 9 0 11-18 0" no longer drop the rest of the path. Arcs with identical endpoints or one zero radius gave NaN points and now end in a straight line per the SVG spec, and an empty d is no path instead of an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
currentColor stays a keyword in inherited fill and stroke and takes the color property of the drawn element. Markers, vector-effect, mix-blend-mode, paint-order with stroke first and preserveAspectRatio other than xMidYMid meet give errors; outlines are allocated by FT_Outline_New, which checks their limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Such an arc added a zero-length edge, while the SVG spec omits it, and empty or whitespace-only points of polygon and polyline are no shape instead of an error, as for an empty d.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pixel coordinates and stroke widths that are not finite or exceed FreeType's limit of 262144 pixels overflowed the conversion to 26.6 and gave wrong images, so they give an error. New tests cover element opacity of fill and stroke, stroke width under a group transform and the file overload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Dashes are cut from the flattened contours in pixels before stroking; patterns finer than FreeType's 1/64 px give an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sharp rects ran in the opposite direction and rounded ones started at x + width - rx, so their dashes were mirrored or shifted compared with browsers; this reverses the point order of sharp rects loaded as lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… foreignObject

A zero-length dash at the offset is drawn, no dash starts at the end of a contour, and a dash through the start of a closed contour gets a join instead of two caps, as in Chromium. Patterns that would give more dashes than a FreeType outline holds fail before the dashes are built, miter limits are clamped to the 16.16 range, and dashed strokes with pathLength and foreignObject elements give errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A use draws the element it references by id as its child, moved by its x and y; references outside the document, symbol targets and cycles give errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…asserts

S reflected the control point of a preceding Q and T that of a preceding C, while SVG reflects it only after a curve of the same kind and uses the current point otherwise. The arc endpoint asserts had an absolute tolerance, which valid arcs far from the origin or with large radii exceeded in Debug; it now grows with the center and radii.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… text

FreeType's rasterizer never ended on outline edges of 32768 pixels or longer, whose coordinate products overflow 32-bit long on Windows and wasm32, and chains of use overflowed the stack; both give errors now. Text without content and symbols outside use draw nothing instead of an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Grantim
Grantim marked this pull request as ready for review December 3, 2026 15:28
Reuse existing helpers (split callback, parsePolyline_, accumulate, designated initializers) and check the root element once; merge overlapping SVG tests into tables without dropping any check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@Fedr Fedr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice piece of work: the parser fixes are valuable on their own and the "error instead of a silently wrong image" policy is mostly followed. A few places where it is not, though:

  1. Strokes under non-uniform transforms are drawn with a wrong width. render_ strokes the already-transformed contours with pixelScale = sqrt(|det A|), i.e. a circular pen of averaged width. Under transform="scale(4,1)" (or any skew), a horizontal line with stroke-width="1" comes out 2x too thick and a vertical one 2x too thin; dash lengths are measured in pixel space with the same averaged factor, so they are off too. Either stroke (and dash) the contours in user space, multiplied by pixelScale for 26.6 precision, and then map the exported outline by A / pixelScale and b with FT_Outline_Transform / FT_Outline_Translate, or return an error when A is not conformal, in line with the rest of the PR.

  2. Units are silently ignored. parseNumber stops at the first non-number character, so stroke-width="10%", stroke-width="0.5mm", width="100%" on a root svg without viewBox, or CSS4 opacity="50%" (clamped to 1) all give a wrong image without an error. Accepting a missing unit or px and rejecting anything else would match the stated policy.

  3. rasterize checks the resolution only with assert. ImageLoad::fromSvg( ..., { -1, 10 } ) in Release makes Canvas allocate size_t( -1 ) * 10 pixels (std::length_error/bad_alloc), and zero gives an empty image. Since this is a public function, please return an error for a non-positive resolution or one above 32767, and mention the limit in the header comment.

  4. Curves are flattened at a fixed 32 segments, whatever the output resolution: a full circle is a 32-gon, whose sagitta at r = 250 px is about 1.2 px, so it is visibly polygonal in a 512-px image. That is fine for ribbon icons, but either make the segment count depend on the pixel size of the curve, or say in the header that the function is meant for small images.

  5. (nit) A subpath whose last point coincides with its first without Z (M0 0 L10 0 L10 10 L0 0, or a polyline ending at its start) is stroked as closed, so it gets a join instead of two caps; with butt caps SVG leaves a notch there. The same check merges dashes across the start. This needs a closed flag next to the contours, so it is fine as a known limitation.

  6. (nit) use cycles and depth are bounded, but fan-out is not: 10 levels of groups that each use the previous one 10 times draw 10^10 elements, and every level with opacity < 1 also allocates a full-size Vector4f canvas. A cap on the total number of drawn elements would close it.

CI is green on all platforms; the CMake wiring mirrors MRSymbolMesh.

…tions and fan-out

Strokes under non-uniform scale or skew, units other than px, a resolution out of 1..32767 and more than 100000 drawn elements give errors; the header says the function is meant for small images.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Grantim

Grantim commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

  1. Done in 5d98c84: stroking under a transform that is not a uniform scale or rotation now returns an error, in line with the rest of the PR (none of the 813 real icons I tested has a non-uniform scale or skew).
  2. Done in 5d98c84: numbers and dash lists accept only an optional px unit; other units and % give an error.
  3. Done in 5d98c84: a resolution out of 1..32767 in either dimension returns "Invalid image resolution", and the header states the limit.
  4. Done in 5d98c84: the header says curves are flattened into 32 segments each whatever the resolution, so the function is meant for small images like icons. Adaptive flattening, or passing the curves to FreeType directly, can come later if needed.
  5. Agreed, it needs a closed flag next to the contours, so it stays a known limitation for now.
  6. Done in 5d98c84: drawing more than 100000 elements returns an error, which bounds the fan-out through use.

Generated with Claude Code

@Fedr Fedr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, 5d98c84 resolves 1, 2, 3, 4 and 6, with tests for each, and 5 is fine as a known limitation.

One remaining gap in item 2: the geometry attributes of shapes and use (x, y, width, height, rx, ry, cx, cy, r, x1...) are still read with tinyxml2's FloatAttribute, whose sscanf( "%f" ) accepts a trailing unit. So <rect width="50%" height="50%"/> or <circle r="2mm"/> still draws at 50 and 2 user units without an error. Reading them through parseNumber in rasterize would close it. That can be a follow-up if you prefer, since LinesLoad::fromSvg shares those readers.

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.

2 participants