Skip to main content

Image conversion

GeneratedAvatar can rasterize SVG content to PNG, JPG, or WebP. Each method returns a new GeneratedAvatar with the converted content and the corresponding content type; the original is left unchanged.

$png = $avatar->toPng(); // defaults to the avatar's size
$jpg = $avatar->toJpg(256, 256, 85); // width, height, quality
$webp = $avatar->toWebp(512, 512);

Signatures​

MethodQuality argumentDefault quality
toPng(?int $width, ?int $height, int $quality)PNG compression level 0–99
toJpg(?int $width, ?int $height, int $quality)JPEG quality 0–10090
toWebp(?int $width, ?int $height, int $quality)WebP quality 0–10090

When width or height is omitted it defaults to the avatar's current size. The returned avatar's size is set to the requested width.

Backend selection​

Conversion is handled by Converters\ImageConverter:

  • If the imagick extension is loaded, it is used. SVG is read directly, resized with a Lanczos filter, and encoded.
  • Otherwise gd is used together with meyfa/php-svg to rasterize the SVG.

JPEG output has no alpha channel, so the image is flattened onto a white background. PNG and WebP preserve transparency.

WebP through gd requires imagewebp (a GD build with WebP support). If it is unavailable, toWebp() throws a RuntimeException — install Imagick or use PNG or JPG instead.

Input handling​

The converter accepts either raw SVG markup or a data: URI (base64 or URL-encoded); the SVG payload is extracted automatically. Any failure during conversion is wrapped in a RuntimeException with the underlying message.

MIME types​

ImageConverter::getMimeType() maps a format string to a MIME type:

FormatMIME type
pngimage/png
jpg, jpegimage/jpeg
webpimage/webp
otherapplication/octet-stream