Using the SVG Image Element for Raster Graphics

Scalable Vector Graphics (SVG) allows developers and designers to combine the precision of vector shapes with pixel-based media through the <image> element. This element acts as a bridge, embedding external raster graphics—such as PNG, JPEG, GIF, and WebP files—directly into an SVG coordinate system. By treating pixel-based files as native SVG nodes, the <image> element enables rich graphical compositions, responsive scaling, and the application of vector effects like masks and filters to standard photographic content.

Linking and Referencing External Files

The <image> element pulls external raster files into the SVG canvas using the href attribute (or xlink:href in older SVG 1.1 documents). The source path can be a relative URL, an absolute URL, or an inline Base64-encoded Data URL.

<svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
  <image href="photo.jpg" x="50" y="50" width="400" height="300" />
</svg>

When the SVG renderer encounters this tag, it fetches the specified file and rasterizes it inside the designated boundary defined by the element’s positioning attributes.

Positioning and Dimensioning

Unlike standard HTML <img> elements that rely on the document’s flow, an SVG <image> element requires explicit placement within the vector viewport:

Controlling Scaling with preserveAspectRatio

Because raster graphics have fixed pixel dimensions, scaling them within an SVG viewport can lead to distortion if the defined width and height do not match the image’s native aspect ratio.

The preserveAspectRatio attribute controls this behavior, functioning similarly to the CSS object-fit property:

Applying Vector Features to Raster Graphics

Once placed in the SVG scene, the raster graphic is integrated into the SVG rendering tree. This allows developers to manipulate pixel-based images using advanced vector capabilities: