Configuring Automatic Media File Optimization for 1C-Bitrix
A catalog page loads 40 product images with a combined size of 8 MB. Google PageSpeed reports "Serve images in next-gen formats" and "Properly size images". Bitrix stores originals in /upload/ and creates resizes via CFile::ResizeImageGet() — but the format remains JPEG/PNG with no automatic WebP conversion. Setting up automatic optimization involves several layers: resizing to actual display dimensions, converting to WebP, lossless compression, and delivery via CDN.
Layer 1: Resize on Original Upload
The standard CFile::ResizeImageGet() creates a resize on the first request and caches the result in /upload/resize_cache/. The primary problem is that originals are stored without compression, and managers upload photos from their phones at 5–10 MB.
Compression on upload via an event handler:
\Bitrix\Main\EventManager::getInstance()->addEventHandler(
'main',
'OnAfterFileSave',
function (\Bitrix\Main\Event $event) {
$file = $event->getParameter('FILE');
// Process images only
if (!in_array($file['CONTENT_TYPE'], ['image/jpeg', 'image/png', 'image/gif'])) {
return;
}
$path = $_SERVER['DOCUMENT_ROOT'] . $file['SRC'];
if (!file_exists($path)) {
return;
}
// Compress using Imagick or GD
\Local\Media\ImageOptimizer::compress($path, $file['CONTENT_TYPE']);
}
);
// /local/lib/Media/ImageOptimizer.php
namespace Local\Media;
class ImageOptimizer
{
public static function compress(string $path, string $contentType): void
{
if (!extension_loaded('imagick')) {
self::compressWithGd($path, $contentType);
return;
}
$img = new \Imagick($path);
// Strip unnecessary metadata (EXIF, ICC)
$img->stripImage();
// Limit maximum original size
$width = $img->getImageWidth();
$height = $img->getImageHeight();
if ($width > 2000 || $height > 2000) {
$img->resizeImage(2000, 2000, \Imagick::FILTER_LANCZOS, 1, true);
}
if ($contentType === 'image/jpeg') {
$img->setImageCompression(\Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(85);
} elseif ($contentType === 'image/png') {
$img->setImageCompression(\Imagick::COMPRESSION_ZIP);
$img->setOption('png:compression-level', '9');
}
$img->writeImage($path);
$img->destroy();
}
private static function compressWithGd(string $path, string $contentType): void
{
if ($contentType === 'image/jpeg') {
$img = imagecreatefromjpeg($path);
imagejpeg($img, $path, 85);
imagedestroy($img);
} elseif ($contentType === 'image/png') {
$img = imagecreatefrompng($path);
imagepng($img, $path, 9);
imagedestroy($img);
}
}
}
Layer 2: WebP Conversion
WebP delivers a 25–35% size reduction compared to JPEG at comparable quality. Browser support is 97%+ (all modern browsers). Strategy: generate a WebP version alongside the original; nginx serves WebP to browsers that support the format.
Generating WebP on resize:
// Override resize logic in /local/php_interface/init.php
\Bitrix\Main\EventManager::getInstance()->addEventHandler(
'main',
'OnAfterGetResizeImagePath',
function (\Bitrix\Main\Event $event) {
$result = $event->getParameter('RESULT');
$src = $result['src'] ?? '';
if (!$src || !preg_match('/\.(jpg|jpeg|png)$/i', $src)) {
return;
}
$localPath = $_SERVER['DOCUMENT_ROOT'] . $src;
$webpPath = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $localPath);
if (!file_exists($webpPath) && file_exists($localPath)) {
\Local\Media\WebpConverter::convert($localPath, $webpPath);
}
}
);
class WebpConverter
{
public static function convert(string $sourcePath, string $destPath): bool
{
if (extension_loaded('imagick')) {
$img = new \Imagick($sourcePath);
$img->setImageFormat('webp');
$img->setOption('webp:method', '6');
$img->setImageCompressionQuality(82);
$img->stripImage();
$img->writeImage($destPath);
$img->destroy();
return true;
}
if (function_exists('imagewebp')) {
$ext = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
$img = match($ext) {
'jpg', 'jpeg' => imagecreatefromjpeg($sourcePath),
'png' => imagecreatefrompng($sourcePath),
default => null,
};
if ($img) {
imagewebp($img, $destPath, 82);
imagedestroy($img);
return true;
}
}
return false;
}
}
Nginx: Serving WebP to Supported Browsers
map $http_accept $webp_suffix {
default "";
"~*webp" ".webp";
}
server {
location ~* ^(/upload/resize_cache/.+)\.(jpg|jpeg|png)$ {
set $img_path $1.$2;
set $webp_path $1.webp;
# Serve WebP if supported and file exists
if ($webp_suffix = ".webp") {
add_header Vary Accept;
try_files $webp_path $img_path =404;
}
try_files $img_path =404;
expires 30d;
add_header Cache-Control "public, immutable";
}
}
Layer 3: Lazy Loading and Responsive Images
In the catalog component template, add loading="lazy" and srcset:
// In the component template: template.php
$img = \CFile::ResizeImageGet($element['PREVIEW_PICTURE'], ['width' => 300, 'height' => 300]);
$img2 = \CFile::ResizeImageGet($element['PREVIEW_PICTURE'], ['width' => 600, 'height' => 600]);
?>
<img
src="<?= htmlspecialchars($img['src']) ?>"
srcset="<?= htmlspecialchars($img['src']) ?> 300w, <?= htmlspecialchars($img2['src']) ?> 600w"
sizes="(max-width: 768px) 300px, 600px"
loading="lazy"
width="300"
height="300"
alt="<?= htmlspecialchars($element['NAME']) ?>"
>
Bulk Optimization of Existing Images
An optimizer for already-uploaded files runs as a Bitrix agent or via CLI:
// Agent: processes 100 files per run
$files = \Bitrix\Main\FileTable::getList([
'filter' => ['CONTENT_TYPE' => ['image/jpeg', 'image/png']],
'limit' => 100,
'offset' => (int)\Bitrix\Main\Config\Option::get('local.media', 'optimize_offset', 0),
])->fetchAll();
foreach ($files as $file) {
$path = \Bitrix\Main\IO\Path::combine(
\Bitrix\Main\Application::getDocumentRoot(),
$file['SUBDIR'], $file['FILE_NAME']
);
if (file_exists($path)) {
\Local\Media\ImageOptimizer::compress($path, $file['CONTENT_TYPE']);
}
}
\Bitrix\Main\Config\Option::set('local.media', 'optimize_offset',
(int)\Bitrix\Main\Config\Option::get('local.media', 'optimize_offset', 0) + 100
);
Setup Timeline
Compression on upload + WebP conversion in nginx + lazy loading in templates — 1–2 business days. Plus bulk optimization of the existing upload/ — an additional 4–8 hours for agent development and execution.







