Skip to main content

Output formats

generate() returns a GeneratedAvatar. It holds the raw content together with a MIME content type and converts to several representations.

The raw content can be one of: SVG markup, binary image data, a data: URI, or an http(s) URL (Gravatar returns a URL).

HTML

$avatar->toHtml();
// SVG content is embedded as a base64 data URI inside an <img> tag:
// <img src="data:image/svg+xml;base64,..." alt="Avatar for John Doe" />

For a data URI or URL source, that value is used directly as src. For other binary content types, the raw content is returned unchanged.

Accessible HTML

accessibleHtml() produces the same <img> tag with role="img" and an aria-label matching the alt text.

$avatar->alt('Profile picture for John Doe');
echo $avatar->accessibleHtml();

Alt text

alt(string) sets explicit alt text. Without it, the alt text is Avatar for {name} when a name is set, otherwise Avatar. Alt text is HTML-escaped.

Data URI

$avatar->toBase64();
// data:image/svg+xml;base64,PHN2ZyB3aWR0aD0i...

If the content is already a data URI it is returned as-is.

URL

$avatar->toUrl();
// Returns the remote URL when the content is one (e.g. Gravatar),
// otherwise a base64 data URI.

Raw content and string casting

$avatar->getContent(); // raw content as stored
$avatar->getContentType(); // e.g. "image/svg+xml", "image/png"
$avatar->toSvg(); // raw content (SVG markup for SVG engines)
(string) $avatar; // same as getContent()

Casting the object to a string returns the raw content, not an <img> tag. Use toHtml() when you need markup.

Raster conversion

toPng(), toJpg(), and toWebp() return a new GeneratedAvatar whose content is the rasterized image. See Image conversion.

$png = $avatar->toPng(512, 512);
echo $png->getContentType(); // image/png
$png->save('/var/www/avatars/user-42.png');

Saving to disk

$avatar->save('/path/to/avatar.svg'); // returns bool

save() creates missing parent directories (mode 0755) and writes the raw content. It returns false if the directory cannot be created or the write fails.

warning

save() writes to the path you pass and creates parent directories. Do not pass an attacker-controlled path; validate or whitelist destinations in application code.

HTTP responses

To return an avatar from a controller, use AvatarResponder. See HTTP responses.