Last updated: August 29, 2026.
AVIF can produce small files, but encoding is CPU-intensive. Generate it once during upload or in a background job rather than on every request.
Convert a JPEG to AVIF
<?php
$image = imagecreatefromjpeg(__DIR__ . '/photo.jpg');
if ($image === false) throw new RuntimeException('Cannot decode JPEG.');
if (!function_exists('imageavif')) throw new RuntimeException('AVIF is unavailable.');
if (!imageavif($image, __DIR__ . '/photo.avif', 55, 6)) throw new RuntimeException('Cannot create AVIF.');
imagedestroy($image);Choose fallbacks
- Test quality settings on representative images.
- Keep a WebP or JPEG fallback when required.
- Serve the result with the image/avif content type.
- Measure encoding time on the production server.
Encode once and cache the result
AVIF encoding is CPU-intensive, so create derivatives during upload or in a background job. Choose quality using representative source images instead of translating a JPEG quality value mechanically.
Measure encoding time, file size, and visible artifacts for photos and graphics. Verify the image/avif response type and retain WebP or JPEG when client support or downstream tools require it.
- Check imageavif availability.
- Bound source dimensions.
- Do not re-encode on every request.
Keep resource limits explicit and make failure cleanup part of the example. Log enough context to diagnose the operation without recording passwords, private message bodies, or uploaded file contents.
Continue with WebP thumbnails, thumbnail fundamentals, and EXIF rotation.
Practical implementation check
Put the operation in a small function or service with explicit inputs and a clear failure result. Test invalid input, missing extensions, permission failures, and concurrent requests. Production logs should identify the operation and record ID without storing secrets or private content. Clean up partially created files or queue records when any later step fails.
Return a clear result to the caller and keep user-facing messages separate from detailed diagnostics. This makes the same code usable from a web request, command-line job, or queue worker.
Reference: PHP imageavif reference.