< Articles


SVG and Raster Image

Why do SVGs scale so nicely? Why do raster images (jpg, png, etc.) become pixelated? And when should I use one over the other?

The answers lie in how an SVG and a raster image are represented in the data. In this short article, we’ll look at the data behind both types of images and how to analyze the tradeoffs.

How are SVGs represented?

First, let’s take a look at the data behind a simple svg.

<svg height="210" width="400">
    <path d="M150 0 L75 200 L225 200 Z" />
</svg>

Here, we have a little bit of XML that tells the computer how to draw the image. M150 0 tells the computer to move to coordinates x = 150 and y = 0 to start drawing. L75 200 creates a line to x = 75 and y = 200. Finally, L225 200 Z tells the computer to draw a line to x = 225 and y = 200 before closing the drawing.

From here, the computer simply fills in the enclosed space with the color that we provide.

From a data perspective, SVGs are simply XML instructions that tell the computer how to draw an image. These instructions ensure our image doesn’t pixelate when changing resolutions. The computer simply redraws our image, retaining its sharpness.

How are raster images represented?

Instead of giving the computer drawing instructions, we provide a bitmap specifying the color of each pixel.

The following example illustrates what this might look like if our bitmap were a Javascript array.

// Indonesian Flagconst red = '#ED4630';
const white = '#FFFFFF';const imageMap = [
    [red, red, red, red, red, red, red, red, red],
    [red, red, red, red, red, red, red, red, red],
    [red, red, red, red, red, red, red, red, red],
    [white, white, white, white, white, white, white, white, white],
    [white, white, white, white, white, white, white, white, white],
    [white, white, white, white, white, white, white, white, white],
];

Here, we’re giving the computer a pixel by pixel map for what colors to use.

The downside of this approach is scaling. This is particularly true for images where small pixels give the impression that a line is curved. Zoom in however, and you’ll notice the lines lose sharpness.

When to use one over the other?

As a general rule of thumb, SVGs are better suited for simple images. If you try converting a complex raster image into an SVG, you’ll notice the file size goes through the roof. There’s simply too many “instructions” within the SVG’s XML data.

With each image, you’ll need to consider file size and scalability. In certain cases, it may make sense to create a larger SVG in oder to maintain sharpness between all devices.

Additional Resources

While there’s a lot of great SVG resources, I’d highly recommend this guide: https://css-tricks.com/lodge/svg .