create('Jane Doe')->setResponsive()->toSvg();
// SVG with custom font family
$customFontSvg = $avatar->create('Michael Chen')
->setFontFamily('Laravolt')
->toSvg();
// Use in HTML
echo '' . $avatar->create('User Name')->toSvg() . '
';
```
### Gravatar Integration
Generate Gravatar URLs with customizable parameters.
```php
create('user@example.com')->toGravatar();
echo $gravatarUrl;
// Outputs: https://www.gravatar.com/avatar/0c5cbf5a8762d91d930795a6107b2ce5814a6ab26e60c7ec6b75bc81c7dfe3ee
// Gravatar with parameters
$customGravatar = $avatar->create('user@example.com')->toGravatar([
'd' => 'identicon', // Default image style
'r' => 'pg', // Rating
's' => 200 // Size in pixels
]);
echo $customGravatar;
// Outputs: https://www.gravatar.com/avatar/...?d=identicon&r=pg&s=200
```
### Runtime Configuration Override
Customize avatar appearance dynamically at runtime.
```php
create('John Doe')->setDimension(150)->toBase64();
// Set dimensions (rectangle)
$avatar->create('Jane Smith')->setDimension(150, 200)->toBase64();
// Customize colors and styling
$customAvatar = $avatar->create('Alice Johnson')
->setBackground('#001122')
->setForeground('#FFFFFF')
->setFontSize(72)
->setFont('/path/to/custom-font.ttf')
->setBorder(2, '#FF5722')
->setShape('square')
->toBase64();
// Method chaining for complex customization
$avatar->create('Bob Wilson')
->setDimension(256, 256)
->setFontSize(96)
->setBackground('#667eea')
->setForeground('#FFFFFF')
->setTheme('colorful')
->setBorder(3, '#aabbcc', 15)
->save('custom-avatar.png', 95);
```
### Theme-Based Avatar Generation
Use predefined themes for consistent styling.
```php
[
'grayscale-light' => [
'backgrounds' => ['#edf2f7', '#e2e8f0', '#cbd5e0'],
'foregrounds' => ['#a0aec0'],
],
'colorful' => [
'backgrounds' => ['#f44336', '#E91E63', '#9C27B0'],
'foregrounds' => ['#FFFFFF'],
],
],
'theme' => ['colorful'], // Active themes
];
$avatar = new Avatar($config);
// Use specific theme
$avatar->create('Sarah Wilson')->setTheme('grayscale-light')->toBase64();
// Randomize between multiple themes
$avatar->create('David Miller')->setTheme(['grayscale-light', 'colorful'])->save('avatar.png');
// Use all available themes
$configAllThemes = array_merge($config, ['theme' => ['*']]);
$avatarAll = new Avatar($configAllThemes);
$avatarAll->create('Emma Davis')->toBase64();
```
### HD Avatar Creation and Export
Generate high-definition avatars with multiple format support.
```php
[
'enabled' => true,
'width' => 512,
'height' => 512,
'fontSize' => 192,
'quality' => [
'png' => 100,
'jpg' => 95,
'webp' => 90,
],
],
];
$hdAvatar = new HDAvatar($hdConfig);
// Create and export single avatar
$result = $hdAvatar->createAndExport('John Doe', 'png');
echo "Avatar URL: " . $result['url'] . "\n";
echo "Hash: " . $result['metadata']['hash'] . "\n";
echo "Dimensions: " . $result['metadata']['width'] . "x" . $result['metadata']['height'] . "\n";
// Export multiple formats
$allFormats = $hdAvatar->exportAllFormats('Emma Davis');
foreach ($allFormats as $format => $urls) {
echo "Format {$format}: {$urls['url']}\n";
}
```
### Batch Avatar Processing
Process multiple avatars efficiently with performance metrics.
```php
batchCreateAndExport($names, 'webp');
echo "Processed: " . $batchResult['batch_info']['total_count'] . " avatars\n";
echo "Time: " . $batchResult['batch_info']['processing_time_seconds'] . " seconds\n";
echo "Average: " . $batchResult['batch_info']['average_time_per_avatar'] . " seconds per avatar\n";
// Access individual results
foreach ($batchResult['avatars'] as $name => $data) {
echo "{$name}: {$data['url']}\n";
}
// Bulk export with custom options
$exported = $hdAvatar->bulkExport(
$names,
'storage/avatars',
'png',
['quality' => 95, 'compression' => 6]
);
```
### Responsive Avatar Sizes
Generate multiple sizes for responsive web design.
```php
[
'thumbnail' => ['width' => 64, 'height' => 64, 'fontSize' => 24],
'small' => ['width' => 128, 'height' => 128, 'fontSize' => 48],
'medium' => ['width' => 256, 'height' => 256, 'fontSize' => 96],
'large' => ['width' => 512, 'height' => 512, 'fontSize' => 192],
'ultra' => ['width' => 1024, 'height' => 1024, 'fontSize' => 384],
],
];
$hdAvatar = new HDAvatar($config);
// Create with responsive sizes
$result = $hdAvatar->createAndExport('Jane Smith', 'webp');
foreach ($result['responsive_urls'] as $size => $url) {
echo "Size {$size}: {$url}\n";
}
// Add custom responsive size at runtime
$hdAvatar->setResponsiveSize('extra-large', 768, 768, 288)
->createAndExport('User Name', 'png');
```
### Storage Optimization and Cleanup
Manage cached avatars with automatic cleanup and monitoring.
```php
[
'disk' => 'local',
'directory' => 'avatars',
'max_storage_mb' => 500,
'max_age_days' => 30,
'compression' => true,
],
];
$hdAvatar = new HDAvatar($config);
// Configure storage optimization
$hdAvatar->configureStorage('local', 'optimized-avatars', 1000); // 1GB limit
$hdAvatar->setCompressionEnabled(true);
$hdAvatar->setMaxFileAge(14); // 14 days
// Get storage statistics
$stats = $hdAvatar->getStorageStatistics();
echo "Storage: {$stats['total_size_mb']} MB ({$stats['usage_percentage']}%)\n";
echo "Files: {$stats['total_files']}\n";
// Optimize storage when needed
if ($stats['usage_percentage'] > 80) {
$optimization = $hdAvatar->optimizeStorage();
echo "Removed: {$optimization['optimization_summary']['files_removed']} files\n";
echo "Saved: {$optimization['optimization_summary']['space_saved_mb']} MB\n";
}
```
### API Response Generation
Create API-ready JSON responses with comprehensive metadata.
```php
apiResponse('Sarah Wilson', 'webp', 'large');
// Returns structured array:
/*
[
'success' => true,
'data' => [
'avatar' => [
'name' => 'Sarah Wilson',
'initials' => 'SW',
'url' => 'https://storage/avatars/abc123_large.webp',
'placeholder' => 'data:image/png;base64,...',
'responsive_urls' => [
'thumbnail' => '...',
'small' => '...',
'medium' => '...',
],
],
'metadata' => [
'size' => 'large',
'format' => 'webp',
'dimensions' => ['width' => 512, 'height' => 512],
'hash' => 'abc12345',
'cache_key' => 'avatar_sarah_wilson_large',
],
],
'timestamp' => '2025-12-11T23:16:45.000Z',
]
*/
echo json_encode($apiResponse, JSON_PRETTY_PRINT);
```
### Health Check and Monitoring
Monitor avatar system health and performance.
```php
healthCheck();
echo "System Status: {$health['status']}\n"; // healthy, degraded, or unhealthy
// Check individual components
foreach ($health['checks'] as $check => $status) {
$statusText = $status ? 'PASS' : 'FAIL';
echo "- {$check}: {$statusText}\n";
}
// Display warnings
if (!empty($health['warnings'])) {
echo "Warnings:\n";
foreach ($health['warnings'] as $warning) {
echo "- {$warning}\n";
}
}
// Access statistics
echo "Storage: {$health['statistics']['storage']['total_size_mb']} MB\n";
echo "Formats: " . count($health['statistics']['export']['supported_formats']) . "\n";
```
### Watermarked Avatar Export
Add watermarks to avatars for branding or copyright protection.
```php
createHD('Company User')
->setBackground('#4f46e5')
->setForeground('#ffffff')
->exportWithWatermark(
'storage/avatars/branded_avatar.png',
'© Company',
'png',
[
'watermark' => [
'position' => 'bottom-right',
'opacity' => 0.3,
'fontSize' => 24,
'color' => '#FFFFFF',
],
'quality' => 95,
]
);
```
### Placeholder Generation for Lazy Loading
Create low-quality placeholders for progressive image loading.
```php
createHD('Lazy User')->toPlaceholder(32, 32);
// Use in HTML with progressive loading
echo ' ';
echo "Placeholder size: " . strlen($placeholder) . " bytes\n";
```
### Sprite Sheet Generation
Create sprite sheets with multiple avatar variations for animations.
```php
'#ff6b6b', 'foreground' => '#ffffff'],
['background' => '#4ecdc4', 'foreground' => '#ffffff'],
['background' => '#45b7d1', 'foreground' => '#ffffff'],
['background' => '#96ceb4', 'foreground' => '#ffffff'],
['background' => '#ffeaa7', 'foreground' => '#2d3436'],
];
// Create sprite sheet
$spriteUrl = $hdAvatar->createSpriteSheet('User Name', $variations, 'png');
echo "Sprite sheet URL: {$spriteUrl}\n";
// Use in CSS animations
echo "
.avatar-sprite {
background-image: url('{$spriteUrl}');
animation: avatar-cycle 2s steps(5) infinite;
}
";
```
### Laravel Integration with Facade
Use the Avatar facade in Laravel applications.
```php
$user,
'avatar' => Avatar::create($user->name)->toBase64(),
]);
}
public function generateAvatar(Request $request)
{
// Create and return as HTTP response
return Avatar::create($request->input('name'))
->setDimension(200)
->setBackground('#667eea')
->toSvg();
}
}
// In Blade template
```
### Standalone PHP Integration
Use the library in non-Laravel PHP projects.
```php
'gd',
'shape' => 'circle',
'width' => 100,
'height' => 100,
'chars' => 2,
'fontSize' => 48,
'fonts' => [__DIR__ . '/fonts/OpenSans-Bold.ttf'],
'foregrounds' => ['#FFFFFF'],
'backgrounds' => ['#f44336', '#E91E63', '#9C27B0'],
'border' => [
'size' => 1,
'color' => 'background',
],
];
// Create avatar instance
$avatar = new Avatar($config);
// Generate and save
$avatar->create('John Doe')->save('output/avatar.png', 90);
// Generate base64 for HTML
echo ' ';
```
### Avatar Information Retrieval
Get comprehensive avatar metadata and configuration.
```php
getAvatarInfo('Technical User');
/*
Returns:
[
'name' => 'Technical User',
'initials' => 'TU',
'dimensions' => ['width' => 512, 'height' => 512],
'styling' => [
'background' => '#4f46e5',
'foreground' => '#FFFFFF',
'font_size' => 192,
'shape' => 'circle',
'border' => ['size' => 1, 'color' => '#4f46e5', 'radius' => 0],
],
'configuration' => [
'hd_enabled' => true,
'responsive_sizes' => [...],
'export_path' => 'avatars',
],
'performance' => [
'cache_enabled' => true,
'compression_enabled' => true,
'storage_disk' => 'local',
],
'hash' => 'abc12345',
'estimated_file_sizes' => [
'png' => '917504 bytes (estimated)',
'jpg' => '131072 bytes (estimated)',
'webp' => '104857 bytes (estimated)',
],
]
*/
echo "Name: {$info['name']}\n";
echo "Initials: {$info['initials']}\n";
echo "Background: {$info['styling']['background']}\n";
echo "HD Enabled: " . ($info['configuration']['hd_enabled'] ? 'Yes' : 'No') . "\n";
```
## Summary
Laravolt Avatar provides a comprehensive solution for generating user avatars from initials, eliminating the dependency on user-uploaded images or third-party services. The library excels in scenarios requiring consistent visual identity across user bases, such as SaaS applications, content management systems, social platforms, and administrative dashboards. Its deterministic color selection ensures users maintain the same avatar appearance across sessions while supporting both quick generation for real-time requests and batch processing for bulk operations.
Integration patterns vary from simple standalone PHP usage to full Laravel framework integration with facade support and service provider auto-discovery. The HD Avatar extension enables production-grade deployments with features like multi-format export (PNG, JPEG, WebP), responsive image generation, storage optimization with automatic cleanup, and RESTful API response formatting. Whether implementing a simple profile picture system or a sophisticated avatar service with CDN integration, caching layers, and health monitoring, the library scales from prototypes to enterprise applications while maintaining clean, testable code through trait-based architecture and interface-driven design.