Back to Blog
Technicalsvgimage-tracingvectorization

Turning a Bitmap Into SVG: How Image Tracing Works

How image tracing turns a bitmap into SVG paths: thresholding, contour following, simplification and smoothing, color tracing, and why logos trace cleanly while photos do not.

LoopalooPublished May 22, 202612 min read

A bitmap and an SVG are two completely different ways of describing a picture. A PNG is a grid of pixels: row by row, each cell holds a color. An SVG is a set of instructions: "draw a path from here, curve through there, fill it black." Image tracing is the act of looking at the pixel grid and reverse-engineering a plausible set of instructions that would redraw it.

That reverse-engineering is lossy and opinionated. There is no single correct vector representation of a pixel grid, so a tracer has to make decisions: where one shape ends and another begins, how smooth an edge should be, how many colors are worth keeping. Those decisions are why a flat two-color logo traces beautifully and a photo of a beach turns into a muddy pile of blobs.

This post walks through a complete tracing pipeline, stage by stage, with small standalone code examples for each step, and explains where the technique works and where it breaks down.

Why photos lose and logos win

Vector tracing wants regions: large, contiguous areas of a single color bounded by a clean edge. A logo is made of regions by design. A corporate mark might be three solid colors with crisp boundaries. Trace it and you get a handful of paths that reproduce the original almost exactly, at any zoom level, in a few kilobytes.

A photograph is the opposite. It is millions of subtly different colors arranged in smooth gradients, with noise on top. There are no clean regions, and if you force a tracer to find them, it either invents thousands of tiny paths (one per noise speckle) or collapses the gradient into a few flat bands and throws away everything that made the photo look like a photo. Either way, the output is often bigger than the original JPEG and looks worse.

So the rule of thumb comes from the mechanics rather than from taste: trace things that are already made of flat regions. Logos, icons, line art, signatures, simple illustrations and screenshots of solid-color UI all qualify. For continuous-tone images, vectorization is the wrong tool.

The pipeline at a glance

A typical tracer runs a fixed sequence of transforms, and each one throws away information in service of the next:

StageInputOutputWhat it discards
DownscaleSource imageA working copy, often under 1,000px on the long edgeResolution
Blur (optional)RGBA pixelsSmoothed RGBAHigh-frequency noise
Threshold / quantizeRGBA pixelsBinary mask(s)Most color information
Contour followBinary maskClosed loops of boundary pointsInterior pixels
Simplify + smoothPoint listsFewer, softer pointsPixel-grid jaggedness and redundant points
Curve fitPoint listsSVG path stringsStraight-line segment data

The downscale step surprises people, but it earns its place. Tracing cost scales with pixel count, and for the kinds of images that trace well, extra pixels mostly add noise rather than useful detail. The result is a vector anyway, so it can be drawn at any size afterwards.

Step 1: collapse color into a binary mask

Contour following needs a yes-or-no answer for every pixel: is this part of a shape or not? Producing that boolean grid is where most of the decisions about trace quality live.

In black-and-white tracing, each pixel is first reduced to a single brightness value (luma), which is then compared to a threshold:

// Rec. 709 weights, which match the sRGB primaries.
// The older Rec. 601 standard uses 0.299, 0.587 and 0.114.
const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const isInk = invert ? luma >= threshold : luma < threshold;

The weights reflect how the eye perceives red, green and blue: green carries most of the perceived brightness and blue very little. Which standard you use matters more than you might expect on saturated colors. A teal of (0, 170, 170) measures about 119 under Rec. 601 and about 134 under Rec. 709, so at the common midpoint threshold of 128 it counts as ink under one definition and as background under the other. Perceptual measures such as CIE L* lightness are another option when you want the threshold to track how light a color looks rather than how it is encoded.

With a threshold of 128, everything darker becomes "shape" and everything lighter becomes "background." The invert flag flips the comparison for light-on-dark art.

That single number is the most important control for line art. A scanned signature with faint strokes needs a higher threshold so the light pixels still count as ink. A bold logo on a busy background needs a lower one so the background does not bleed in. There is no universally right value, which is why tracing tools expose it as a slider.

Transparency needs a decision too

A PNG logo on a transparent background raises a question the threshold cannot answer on its own: what color is a pixel with no opacity? Browsers store canvas pixels with premultiplied alpha, so a fully transparent pixel usually reads back as rgba(0, 0, 0, 0), which is black with zero opacity. A tracer that looks only at the RGB channels sees the logo sitting on a solid black field.

There are two sensible answers. You can composite the image onto a matte color (usually white) before thresholding, which is what you would see if you placed the PNG on a white page. Or you can treat the alpha channel itself as the mask, so any pixel that is at least half opaque is inside the shape and the color threshold is ignored.

Blurring before thresholding

A hard threshold is brutal to noise. A single stray dark pixel in a light region becomes its own tiny shape. A light Gaussian blur before thresholding softens this. The standard way to implement it is as two one-dimensional passes, horizontal then vertical:

// One horizontal pass over a single channel. Running the same pass
// vertically on the result completes the 2D Gaussian blur.
function blurRows(src, dst, width, height, kernel) {
  const half = (kernel.length - 1) / 2;
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      let sum = 0;
      for (let k = 0; k < kernel.length; k++) {
        const sx = Math.min(width - 1, Math.max(0, x + k - half));
        sum += src[y * width + sx] * kernel[k];
      }
      dst[y * width + x] = sum;
    }
  }
}

This works because the Gaussian is separable. A true 2D convolution costs work proportional to the square of the kernel diameter for every pixel, while two 1D passes give an identical result at a cost proportional to the diameter. A radius of a pixel or so is usually enough to take the edge off sensor noise without dissolving thin strokes.

Step 2: follow the contours

With a binary grid in hand, the next job is to find the outlines of the filled regions. There are two broad ways to do it, and the difference shows up in the output.

Tracing through pixel centers

The classic approach is Moore-neighbor tracing, which walks only the border pixels: ink pixels with at least one background pixel among their eight neighbors. Interior pixels carry no shape information and are never visited. Starting from the first ink pixel found by a top-to-bottom, left-to-right scan, the tracer repeatedly sweeps clockwise around the current pixel, starting just past the pixel it arrived from, and steps to the first ink neighbor it meets:

// Neighbor offsets in clockwise order (y grows downward): E, SE, S, SW, W, NW, N, NE
const DX = [1, 1, 0, -1, -1, -1, 0, 1];
const DY = [0, 1, 1, 1, 0, -1, -1, -1];

function traceOutline(isInk, startX, startY) {
  const outline = [];
  let x = startX;
  let y = startY;
  let back = 4;       // the scan guarantees the pixel to the west is background
  let firstMove = -1;
  for (;;) {
    let move = -1;
    for (let i = 1; i <= 8; i++) {
      const d = (back + i) % 8;
      if (isInk(x + DX[d], y + DY[d])) { move = d; break; }
    }
    if (move === -1) return [[x, y]];          // an isolated pixel
    if (x === startX && y === startY) {
      if (move === firstMove) break;           // leaving the start the same way twice: closed
      if (firstMove === -1) firstMove = move;
    }
    outline.push([x, y]);
    x += DX[move];
    y += DY[move];
    back = (move + 4) % 8;                     // direction pointing back where we came from
  }
  return outline;
}

Starting each sweep just past the previous pixel is what keeps the walk hugging the edge instead of cutting across the shape. The stopping rule is subtle. Stopping the first time the walk returns to its start fails on shapes that pinch through the start pixel, so this version stops only when it would leave the start in the same direction as the first time (known as Jacob's stopping criterion).

The result is an ordered list of points outlining one region, with every point sitting on a pixel center. That has a cost: a polygon drawn through the centers of the boundary pixels cuts half a pixel off every edge, and a lone pixel collapses to a single point with no area at all.

Tracing along the cracks between pixels

The alternative, used by Potrace and other careful tracers, walks the edges between pixels instead. Every vertex lands on a grid corner, and the polygon encloses exactly the ink pixels it was traced from. A lone pixel at (2, 3) becomes the unit square from (2, 3) to (3, 4), with an area of exactly one.

This approach also makes holes straightforward. Every boundary between ink and background gets traced, including the inner boundary of the hole in a letter O. Outer boundaries come out running one way and hole boundaries the other, which matters in Step 4.

Whichever method you use, this is also the natural place to filter noise. Regions below a minimum area (or contours below a minimum length) are dropped, so a three-pixel speck never becomes a path. Raise the minimum to ignore larger specks, lower it to keep fine detail.

Step 3: simplify and smooth

A raw contour has one point per boundary pixel or pixel edge. A straight diagonal edge becomes a staircase of dozens of points, and emitting that verbatim produces a huge, jagged path. Two cleanup passes fix it.

Simplification usually means the Ramer-Douglas-Peucker algorithm. RDP keeps the two endpoints of a run of points, finds the point farthest from the straight line between them, and recurses only if that distance exceeds a tolerance:

function simplify(points, tolerance) {
  if (points.length < 3) return points;
  const [ax, ay] = points[0];
  const [bx, by] = points[points.length - 1];
  const length = Math.hypot(bx - ax, by - ay);
  let farthest = 0;
  let index = 0;
  for (let i = 1; i < points.length - 1; i++) {
    const [px, py] = points[i];
    const distance = length === 0
      ? Math.hypot(px - ax, py - ay)
      : Math.abs((bx - ax) * (ay - py) - (ax - px) * (by - ay)) / length;
    if (distance > farthest) { farthest = distance; index = i; }
  }
  if (farthest <= tolerance) return [points[0], points[points.length - 1]];
  const left = simplify(points.slice(0, index + 1), tolerance);
  const right = simplify(points.slice(index), tolerance);
  return left.slice(0, -1).concat(right);
}

With a tolerance of 1 pixel, a 21-point staircase running from (0, 0) to (10, 10) collapses to its 2 endpoints, while a genuine corner survives because the corner point sits far from the chord. This is where most of the point-count reduction (and the file-size win) comes from. A closed loop needs one extra step: split it at two far-apart points and simplify each half, since a chord between identical endpoints has no direction to measure against.

Smoothing rounds off what is left of the pixel staircase. The simplest version pulls each point part of the way toward the midpoint of its two neighbors:

function smoothLoop(points, amount) {
  const n = points.length;
  return points.map(([x, y], i) => {
    const [px, py] = points[(i - 1 + n) % n];
    const [nx, ny] = points[(i + 1) % n];
    return [x + ((px + nx) / 2 - x) * amount, y + ((py + ny) / 2 - y) * amount];
  });
}

This is a small Laplacian smoothing step. Applied blindly, it also softens corners that should stay sharp, so better tracers measure the turn angle at each vertex first and leave alone any corner sharper than a chosen angle. A cross keeps its right angles while the staircase along its arms is rounded away. How much to smooth is a matter of taste; the corner threshold is what keeps it from damaging the shape.

Step 4: the output is paths, not pixels

The final stage turns each loop into an SVG path string. Rather than connecting points with straight lines, a simple and effective trick is to fit quadratic Bézier curves: each vertex becomes a control point, and the midpoints between neighboring vertices become the segment endpoints.

function loopToPath(points) {
  const n = points.length;
  const mid = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
  const fmt = (p) => p[0].toFixed(1) + ' ' + p[1].toFixed(1);
  let d = 'M ' + fmt(mid(points[n - 1], points[0]));
  for (let i = 0; i < n; i++) {
    d += ' Q ' + fmt(points[i]) + ' ' + fmt(mid(points[i], points[(i + 1) % n]));
  }
  return d + ' Z';
}

This produces a continuous, smooth curve through the simplified points without solving for true spline tangents. Where a vertex was marked as a sharp corner, you emit a straight L to it instead of a curve. Writing coordinates to one decimal place keeps the file small while staying well below anything you could see.

Holes need care. A fill-rule only applies within a single path element, so a ring traced as two separate filled paths simply paints the middle black. The outer boundary and its holes have to be subpaths of one path:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  <path fill="#000000" fill-rule="evenodd"
        d="M10 10 L90 10 L90 90 L10 90 Z M30 30 L30 70 L70 70 L70 30 Z"/>
</svg>

With fill-rule="evenodd", a point is filled only if a ray from it crosses the outline an odd number of times, so the inner square becomes a hole. The inner loop here also runs in the opposite direction to the outer one, which means it would cut out a hole under the default nonzero rule as well. Crack-following tracers get this orientation for free.

The payoff is in the word paths. The output is resolution-independent: scale a 320px logo up to a billboard and the curves stay crisp, because the browser is re-evaluating Bézier math rather than stretching pixels.

Color tracing: one binary mask per color

Everything above is single-channel. Multi-color tracing reuses the same machinery N times. First, the image is reduced to a small palette, often six to a dozen colors. Median cut is the classic method: it repeatedly takes the group of pixel colors whose widest channel spans the most, sorts it along that channel, and splits it at the median, until it has the requested number of groups. Each group is then averaged to a representative color.

// One median-cut split: sort a box of colors along its widest channel
// (0 = red, 1 = green, 2 = blue) and cut it in half at the median.
box.sort((a, b) => a[channel] - b[channel]);
const middle = Math.floor(box.length / 2);
const halves = [box.slice(0, middle), box.slice(middle)];

Alternatives include simply taking the most common exact colors (ideal for flat digital art that already has only a few) and k-means clustering in a perceptual color space such as CIE Lab, which tends to group colors the way the eye does.

Then, for each palette color, the tracer builds a binary mask of the pixels that quantized to that color and runs the full contour, simplify, smooth and curve-fit pipeline on it. Each color becomes its own set of filled paths in the output SVG.

This is also why color tracing degrades gracefully on logos and badly on photos. A six-color logo maps cleanly onto six masks. A photo of a sunset forced into six colors becomes six posterized bands with ragged boundaries, and tracing those boundaries gives you a jagged, oversized SVG that looks like a screen-printing error. The quantization is doing its job; the input just is not made of flat colors.

When to reach for it

Use it forSkip it for
Logos and brand marksPhotographs
Icons and pictogramsAnything with gradients
Line art and signaturesDetailed illustrations with soft shading
Recovering a vector from a low-res rasterTextures and noise
Single-color silhouettes for cutting/engravingScreenshots full of antialiased text

Tracing answers the question "what flat shapes approximate this image?", and it only gives a good answer when the image is already made of flat shapes.

Related tools on Loopaloo

To try these ideas on your own images, use the Image to SVG Tracer. Upload a logo and adjust the threshold (measured on Rec. 709 luma, Rec. 601 luma or CIE L*), the number of colors and how they are grouped (most common, median cut or k-means in CIE Lab), how transparency is treated, and the simplify, smooth, corner and minimum-area settings, and the SVG updates as you go. It tells you how many regions and holes it found, how many points survived simplification, and how many pixels the vector differs from the picture it came from. Once you have an SVG, the SVG Optimizer can strip editor data, metadata and redundant precision to shrink the file further. To go the other way, rendering a vector down to a fixed-size image for a thumbnail or social card, use SVG to PNG/JPG. All three run entirely in your browser, so nothing you upload leaves your machine.

Related Tools

Related Articles