Can AI Clean Up SVG Markup? Repair Tests With Pixel Diffs

We ran AI SVGs through Haiku 5.5 and SVGO and measured bytes, nodes and pixel diffs: what breaks shapes, how to remove backgrounds and set currentColor.

Amit Yadav
20 min read
On this page

Yes, AI can clean up SVG markup, but it cannot shrink path data. In our test on 2026-11-05, Claude Haiku 5.5 restructured small icons better than any script, then copied traced paths nearly unchanged, so a traced gear stayed at 5,152 bytes where an 88-line SVGO script reached 1,936.

We took 12 real files: icons written by Haiku, bitmaps traced with potrace, and vendor samples from AI SVG tools. For each repair we recorded bytes, nodes and a pixel diff against the original render at 24 and 96 px in Chrome. How these files were made, and which generators are worth using, is in our AI SVG generator test. This page only covers the repair.

Quick answer

  • Model or script: use a model to restructure a small icon by hand. Use a script for anything traced. The model kept every node on all 10 traced runs.
  • Background: never delete every full-size rect. Four Haiku gears kept one inside a mask, and deleting it erased the whole icon.
  • Precision: it cuts bytes, not nodes. Rounding to 0 decimals is safe on a 1024 canvas and destroys a 24 canvas. Files with arcs should keep 3 decimals.
  • Nodes: retrace the bitmap with higher tolerance. Curve simplifying after the trace visibly warped every shape we tried.
  • Colors: one color for a whole icon only works if the source has one color. Applied to a colored file, it turned one sample into a solid square.

Can a model do the clean?

We sent the same prompt to Haiku 5.5, 5 times per file: remove the background and anything invisible, use currentColor, merge paths, make it as small as you can, keep the drawing identical.

"Changed" counts the share of pixels that differ by more than 32 out of 255 on white, so 0 means no visible change at that threshold. A node is one path segment or one basic shape.

FileRaw bytesSVGO defaultOur scriptHaiku medianHaiku runs over 1% changed at 96 px
Haiku gear with mask1,1369499266480 of 3
Haiku gear with overlaps8074514283642 of 5
Potrace gear5,7204,3531,9365,1520 of 5
Potrace of AI coffee cup17,61010,6407,01615,6360 of 5
SVG AI line icon3,5343,5343,5293,5400 of 5
SVGMaker logo on dark canvas3,3672,567See below2,9500 of 5

Three things stand out:

  • Structure is where the model wins. It replaced the mask gear with one even-odd path plus <use> copies of a tooth, which SVGO never does. It also read the SVGMaker file correctly in all 5 runs: canvas gone, knockouts merged, 0 pixels changed against the logo shape.
  • Path data is where it stops. Node counts on the traced files stayed at 112 and 413 in every run. The output was often larger than SVGO's because the model retyped the coordinates.
  • It can break a simple file. On the overlap gear, 2 of 5 runs changed the drawing, by 1.46% and 3.68% at 96 px. Compare the render every time.

Cost is the other gap. Each file took a median of 10 to 27 seconds and 2,300 to 8,900 output tokens. The script took 1 to 18 ms. Of 30 calls, 28 returned an SVG and 2 failed with a network error, both on the mask gear.

The repair script

This is the file we measured, unchanged. It adds a missing viewBox, removes a canvas shape, turns pure black into currentColor, picks precision from the canvas size, and leaves masks alone. It needs SVGO 4. For a one-off file with no script, try the SVG optimizer, and our SVGO settings test covers more options.

// node clean-svg.mjs in.svg > out.svg (SVGO 4)
import { readFileSync } from 'node:fs';
import { optimize } from 'svgo';

const num = Number.parseFloat;

// True for a path of straight lines that only visits the four canvas corners.
function isBoxPath(d, [x, y, w, h]) {
  const parts = d.match(/[a-z]|-?\d*\.?\d+(?:e-?\d+)?/gi) ?? [];
  const pts = [];
  let i = 0, cx = 0, cy = 0, cmd = '';
  while (i < parts.length) {
    if (/[a-z]/i.test(parts[i])) cmd = parts[i++];
    const k = cmd.toLowerCase(), rel = cmd === k;
    if (k === 'z') continue;
    if (k === 'm' || k === 'l') {
      cx = num(parts[i++]) + (rel ? cx : 0);
      cy = num(parts[i++]) + (rel ? cy : 0);
    } else if (k === 'h') cx = num(parts[i++]) + (rel ? cx : 0);
    else if (k === 'v') cy = num(parts[i++]) + (rel ? cy : 0);
    else return false; // a curve means it is not a plain box
    pts.push([cx, cy]);
  }
  const near = (a, b) => Math.abs(a - b) <= Math.max(w, h) * 0.001;
  return new Set(pts.map(String)).size === 4 && pts.every(
    ([a, b]) => (near(a, x) || near(a, x + w)) && (near(b, y) || near(b, y + h)),
  );
}

function coversCanvas(el, box) {
  const a = el.attributes;
  if (a.transform && !/^translate\(\s*0[\s,]+0\s*\)$/.test(a.transform)) return false;
  if (el.name === 'path') return isBoxPath(a.d ?? '', box);
  if (el.name !== 'rect' || num(a.rx) > 0 || num(a.ry) > 0 || num(a.x) > 0 || num(a.y) > 0) return false;
  const full = (v, size) => v === '100%' || num(v) >= size;
  return full(a.width, box[2]) && full(a.height, box[3]);
}

// Removes the first painted shape if it fills the canvas. Never looks inside
// defs, mask, clipPath, pattern or symbol, where a full-size rect does a job.
const removeCanvasBackground = {
  name: 'removeCanvasBackground',
  fn: () => ({
    element: {
      enter(node, parent) {
        if (node.name !== 'svg' || parent.type !== 'root') return;
        const a = node.attributes;
        a.viewBox ??= `0 0 ${num(a.width)} ${num(a.height)}`;
        a.fill ??= 'currentColor';
        const box = a.viewBox.trim().split(/[\s,]+/).map(Number);
        const skip = /^(defs|title|desc|metadata|style|mask|clipPath|symbol|pattern|linearGradient|radialGradient)$/;
        let list = node, first;
        for (;;) {
          first = list.children.find((c) => c.type === 'element' && !skip.test(c.name));
          const g = first?.attributes;
          if (first?.name === 'g' && !g.mask && !g['clip-path'] && !g.filter && !g.transform) list = first;
          else break;
        }
        if (first && coversCanvas(first, box)) list.children = list.children.filter((c) => c !== first);
      },
    },
  }),
};

export function cleanSvg(svg) {
  const w = num(svg.match(/viewBox="\s*[-\d.]+[\s,]+[-\d.]+[\s,]+([\d.]+)/)?.[1] ?? svg.match(/\swidth="([\d.]+)/)?.[1] ?? 24);
  // Rounding bends arcs that are close to a half circle, so files with arcs keep 3 decimals.
  const p = /\sd="[^"]*a/i.test(svg) ? 3 : w >= 1000 ? 0 : w >= 100 ? 1 : 3;
  return optimize(svg, {
    multipass: true,
    plugins: [
      removeCanvasBackground,
      {
        name: 'preset-default',
        params: {
          overrides: {
            convertPathData: { floatPrecision: p, makeArcs: false, convertToQ: false, straightCurves: false },
            cleanupNumericValues: { floatPrecision: p },
            convertColors: { currentColor: /^(#0+|black|rgb\(0,\s*0,\s*0\))$/i },
          },
        },
      },
      'removeDimensions',
    ],
  }).data;
}

if (process.argv[2]) process.stdout.write(cleanSvg(readFileSync(process.argv[2], 'utf8')));

Results across the sample, with no canvas shape to remove:

FileRawScriptNodes before, afterChanged at 24 pxChanged at 96 px
Haiku gear with mask1,13692611, 140%0%
Potrace gear5,7201,936112, 1120.17%0.43%
Potrace coffee cup3,2731,10982, 770.35%0.18%
Potrace of AI coffee cup17,6107,016413, 4100%0.11%
neoSVG sample32,50411,303829, 8070%0.18%
Vendor sample, 512 canvas42,19918,911998, 9980.17%0.90%

We also ran it on 439 icons sampled from Lucide, Tabler, Heroicons and Feather, which it should not harm. The worst change was 0.25% at 96 px, the same as default SVGO on those files.

Remove a background without deleting the icon

A full-size shape is only a background if it is painted first and outside any mask. This page used to tell you to delete any rect that covers the viewBox. That advice breaks real output.

Four of 15 unprompted Haiku icons, all gears, had <rect width="24" height="24" fill="white"/> inside a <mask>. There it means "show everything", and it is not a background. Deleting it took the icon from about 40% ink to nothing.

Four renders of a Haiku gear. The original and the script output show the gear. Deleting the full-size rect or setting every color to one value leaves a blank box.

How often a real background turned up:

SourceFilesCanvas fully paintedRemoved by the script
Haiku output4300
Potrace output500
Vendor samples32175

The 5 hits are SVGMaker files that use a box path, not a rect, so a search for <rect finds nothing. The other 12 do not start with a plain rectangle, so the script leaves them for you to edit by hand.

The false positive check was 20,119 SVG files from five icon packages. No painted shape was removed. The rule did strip Tabler's invisible fill="none" box from its 6,257 files, which changes nothing on screen.

The old "ghost vectors" warning did not hold up either. We searched all 84 files for shapes with no fill and no stroke, or with zero opacity, and found none.

Knocked-out logos need flattening

SVGMaker logos paint a dark canvas, then a light shape, then more dark shapes on top. Removing the canvas leaves a white logo on nothing, and the "holes" are still dark paint. Merge it into one path with paper.js, run in a browser page:

// Set width and height to the viewBox size first, or import scales the paths.
const item = paper.project.importSVG(svg, { expandShapes: true, insert: true, applyMatrix: true });
const shapes = item.getItems({ class: paper.PathItem })
  .filter((i) => !(i.parent && i.parent.className === 'CompoundPath'));
const canvas = shapes[0].fillColor;
const nearCanvas = (c) => Math.hypot(c.red - canvas.red, c.green - canvas.green, c.blue - canvas.blue) < 0.25;
let ink = null;
for (const s of shapes.slice(1)) {
  if (!s.fillColor) continue;
  if (nearCanvas(s.fillColor)) { if (ink) ink = ink.subtract(s, { insert: false }); }
  else ink = ink ? ink.unite(s, { insert: false }) : s;
}
const d = ink.pathData;

Against the logo shape, four two-color files changed by at most 0.17% at 24 px and 0.05% at 96 px. The first went from 3,367 to 2,389 bytes. A fifth file with three colors came out wrong, 52.78% changed, because this method only keeps one color.

Replace hard-coded colors with currentColor

The find and replace on fill="#000000" this page used to recommend missed every other way of writing black. Potrace writes fill="black", so it matched nothing on our traced files.

SVGO's convertColors takes one string, one regex or true. It compares text, not color:

Written in the file'#000000''black'/^#0+$/true
fill="#000000"YesNoYesYes
fill="#000"NoNoYesYes
fill="black"NoYesNoYes
fill="rgb(0,0,0)"NoNoNoYes
style="fill:#000000"NoNoNoNo
No fill at allNoNoNoNo

The last row needs fill="currentColor" on the root, which the script adds. A style attribute needs converting first, and our CSS color guide covers what to do with the result.

true is the risky one, since it paints every color the same. Pixels changed at 96 px against the original:

FileWith currentColor: trueWhat happened
Haiku gear with mask0%SVGO skips masks
Haiku coffee cup, 5 colors34.11%Five colors become one
SVG AI line icon3.50%Its colors become one
SVGMaker logo27.83%Solid square
neoSVG sample99.85%Solid square

A regex over every fill and stroke is worse. It rewrites the white inside a mask too, and that erased the mask gear (38.82% changed, third panel above). Use one color only when the source has one, and keep multicolor art as it is. The script only converts pure black.

Lower precision without bending curves

Precision is decimals per coordinate, so its effect depends on the canvas. Zero decimals gives 1,024 steps across a 1024 box and 24 steps across a 24 box.

File and canvasDecimalsBytesChanged at 24 pxChanged at 96 px
Potrace gear, 102434,3530%0%
Potrace gear, 102412,4061.04%0.66%
Potrace gear, 10241, conversions off2,8940%0.05%
Potrace gear, 10240, conversions off1,9430%0.40%
Haiku bell, 2412660%0.33%
Haiku bell, 2402604.86%2.89%
Haiku gear, 24088916.15%7.86%
Heroicons magnifier, 242296not measured5.18%
Heroicons magnifier, 243308not measured0%

Three rules come out of this:

  • At low precision, turn off makeArcs. The Potrace gear at 1 decimal went from 1.04% changed to 0.17% at 24 px with makeArcs: false alone, for 394 more bytes. "Conversions off" in the table also sets straightCurves and convertToQ to false, as the script does.
  • Keep 3 decimals if the file has arcs. The magnifier's arc is close to a half circle, so rounding to 2 decimals changed 5.18% of pixels for 12 bytes saved. The script's arc rule fixed this. It also means the SVG AI files, which contain arcs, gain almost nothing from it.
  • Do not rescale to 24 units to save bytes. The gear at 24 units with 1 decimal was 1,842 bytes and 3.97% changed. Left at 1024 with 0 decimals, it was 1,943 bytes and 0.40% changed.

Precision does not reduce nodes, as this page used to claim. Going to 0 decimals took one vendor file from 926 to 865 nodes.

Reduce nodes: retrace, do not simplify

SVGO left node counts almost unchanged on every traced file. The obvious next step, a curve simplifier, did worse than expected.

paper.js simplify() refits curves through the anchor points and ignores the handles, so it warps traced shapes at any tolerance. On the Potrace gear at tolerance 0.5, it changed 6.08% of pixels at 24 px and 6.37% at 96 px, for 88 nodes against 112:

Three renders of a traced gear. The original and the script output match at 5,720 and 1,936 bytes. The paper.js simplify version has a lumpy outline and a misshapen center hole.

If you still have the bitmap, set a higher tolerance in the tracer. These runs use the potrace npm package, then default SVGO, compared with the normal trace:

BitmapSettingBytesNodesChanged at 24 pxChanged at 96 px
Clean gearDefault4,3531120%0%
Clean gearoptTolerance: 12,126511.56%0.81%
AI coffee cupDefault10,6404100%0.04%
AI coffee cupoptTolerance: 19,7043800.35%0.17%
AI coffee cupturdSize: 1005,6961990.52%0.40%

turdSize removes small specks, which is where most of the AI bitmap's nodes went. Setting alphaMax: 0 raised the gear to 774 nodes, so leave it alone.

Fix the viewBox and padding

The neoSVG sample in our main set had width and height with no viewBox. Set to 96 px, it shows only the top-left corner of the drawing, changing 21.54% of pixels against the fixed version. The fix is viewBox="0 0 1024 1024", which the script adds.

Padding varied much more than the 2 units in 24 (8.3%) that most icon sets use:

FileLeftTopRightBottom
Haiku gear with mask8.3%8.3%8.3%8.3%
Haiku coffee cup9.4%-1.6%15.1%9.4%
Potrace of AI coffee cup21.4%13.5%1.0%1.0%
SVG AI line icon24.5%28.1%16.1%10.4%

To fix it, change the viewBox and leave the paths alone. Take the ink box, use the longer side divided by 5/6 as the new size, and center it. The SVG AI icon became 124.5 158.25 531 531, and its ink at 96 px went from 469 to 869 pixels, nearly double, in the same space.

The negative value on the coffee cup is steam clipped by the canvas, 12 pixels at 128 px. Measure from a render, not getBBox(). In Chrome 156 it returned 12 0 96 116 for that file even with the { stroke: true } option, so stroke width is not counted.

Also remove preserveAspectRatio="none", which SVGMaker adds. On its non-square files, a square render stretched the drawing and changed 16.58% and 11.11% of pixels at 96 px.

Merge duplicates and overlaps

Overlaps matter less than most guides say. This page used to claim that any CSS opacity darkens overlapping areas, and that is only true in some cases. On a Haiku gear with overlapping strokes, at 192 px:

CSSOverlap pixels darker
svg { opacity: .5 }0
svg { stroke-opacity: .5 }2,355
path, circle, line { opacity: .5 }2,355

Opacity on the root treats the icon as one group, so you do not need to merge paths for it. The inherited fill-opacity and stroke-opacity do paint each shape separately.

Merging tools have limits:

  • Strokes: paper.js unite() ignores them. Run on that stroke gear, it changed 25.28% of pixels at 96 px. Convert strokes to outlines first, which we did not test.
  • mergePaths with force: true: caused no change on our 12 files. On two overlapping even-odd squares we wrote ourselves, the overlap became a hole, 6.25% changed. Default settings kept them separate.

Exact duplicates were rare: 1 file of 84 had one, a vendor sample. Removing it saved 644 bytes and changed no pixels. SVGO does not remove these. On a bell we duplicated ourselves, the doubled edges gained 9.3% ink at 24 px, 7.64% of pixels changed, and SVGO kept all three paths. This removes exact copies:

const seen = new Set();
const out = svg.replace(/<(path|circle|rect|line|ellipse|polyline|polygon)\b[^>]*\/>/g, (m) => {
  const key = m.replace(/\s+/g, ' ');
  if (seen.has(key)) return '';
  seen.add(key);
  return m;
});

Before you repair a 900-node trace for a common symbol, check the 243 icon libraries. A drawn icon such as Lucide needs no repair at all.

SVGO settings that break shapes

Default SVGO 4 was safe on all 12 files: at most 0.04% changed at 96 px, and one pass matched multipass to within 1 byte. Most damage comes from settings you add:

SettingEffect at 96 px
removeViewBox6.58% to 41.51% changed on 11 of 12 files
convertColors with trueUp to 99.85% changed on multicolor files
0 decimals on a 24 canvasUp to 7.86% changed
makeArcs and convertToQ at low precision0.66% against 0.05%, Potrace gear at 1 decimal
removeDimensions, reusePaths, sortAttrs, removeOffCanvasPaths, convertStyleToAttrsNo change beyond default

removeXMLNS also rendered the same inline, but we did not test it in an <img> tag, where a file without a namespace should fail.

What we did not test

  • Tools: Illustrator, Figma and Inkscape are not installed here, so their simplify and outline commands are unmeasured. This page used to recommend Illustrator's Simplify and Figma's Union without any test. We also did not test other tracers or other language models.
  • Sample size: 12 main files, 84 scanned for duplicates, 5 model runs per file. Vendor files are homepage samples, not results of our prompts, and are likely their better work.
  • Model: one prompt with no system message and no retries beyond one network retry. A better prompt could change the results.
  • Renderer: Chrome only. We did not check Firefox or Safari.
  • Diff limits: the 32 of 255 threshold hides small edge changes, and a low score does not prove a shape is right at sizes we did not render.
  • False positive scan: the 20,119-file background check ran on a longer draft of the same rule. The published script was checked by render on 439 icons and on the sample files.

Versions, installed 2026-11-05: SVGO 4.1.0, paper 0.17.0, potrace 2.1.8, Chrome 156.0.8078.47, model claude-haiku-5-5.

Can AI clean up SVG markup?
Partly. In our test Haiku 5.5 removed backgrounds, set currentColor and restructured small icons well, with under 1% of pixels changed at 96 px on 26 of 28 runs. It did not reduce nodes on traced files, and 2 of 5 runs changed the drawing on one simple icon. Compare the render after every run.
How do I repair a broken SVG file?
Check that it has a viewBox first, since without one the icon shows at the wrong size or cropped. Then run SVGO at default settings, and only then remove the background and replace colors. If it still fails to display, open it in a browser to see the parser error.
How low can SVG precision go?
It depends on the canvas. On a 1024 canvas with no arcs, 0 decimals changed under 0.5% of pixels. On a 24 canvas, 0 decimals changed up to 16%. Keep 3 decimals on any file with arc commands.
Does SVGO reduce the number of nodes?
Barely. On traced files it went from 413 to 410 and from 82 to 77. To cut nodes, retrace with a higher tolerance. The gear fell from 112 to 51 nodes with a tolerance of 1.
How do I remove a white background from an SVG?
Delete the first painted shape if it fills the canvas, and leave any full-size rect inside a mask, clipPath or pattern. Removing a white rect from inside a mask erased the whole icon in our test. Backgrounds can also be plain paths, so a search for rect can miss them.
Does CSS opacity darken overlapping SVG shapes?
Not when set on the root svg, which is painted as one group. We counted 0 darker pixels. Opacity on each shape, or inherited stroke-opacity and fill-opacity, did darken overlaps.

Related posts

Share this post