blazy_blurry_placeholder-8.x-2.1/blazy_blurry_placeholder.module
blazy_blurry_placeholder.module
<?php
use Drupal\image\Entity\ImageStyle;
/**
* Implements hook_theme().
*/
function blazy_blurry_placeholder_theme($existing, $type, $theme, $path) {
return [
'blazy_blurry_placeholder_image' => [
'variables' => [
'alt' => '',
'image' => '',
'image_style' => '',
'title' => '',
'url' => '',
],
],
];
}
/**
* Prepares variables for the blazy_blurry_placeholder_image theme.
*/
function template_preprocess_blazy_blurry_placeholder_image(&$variables) {
/** @var \Drupal\file\Entity\File $image */
$image = $variables['image'];
// The image doesn't exist on disk - display it without blazy.
$image_uri = $image->getFileUri();
if (!file_exists($image_uri)) {
$variables['image'] = [
'#theme' => 'image',
'#uri' => file_url_transform_relative(file_create_url($image_uri)),
'#attributes' => [
'title' => !empty($variables['title']) ? $variables['title'] : NULL,
'alt' => !empty($variables['alt']) ? $variables['alt'] : NULL,
],
];
return;
}
// Build the image with the desired image style, if available.
if (!empty($variables['image_style'])) {
$style = ImageStyle::load($variables['image_style']);
$image_uri = $style->buildUri($image_uri);
if (!file_exists($image_uri)) {
$style->createDerivative($image->getFileUri(), $image_uri);
}
}
// Get the sizes of the image so we can make the placeholder have the same size.
$placeholder_image_uri = $image_uri;
$image_size = getimagesize($image_uri);
$variables['width'] = $image_size[0];
$variables['height'] = $image_size[1];
// Create the image with the blazy_blurry_placeholder image style (width: 20px, height: auto)
$style = ImageStyle::load('blazy_blurry_placeholder');
$placeholder_image_uri_with_style = $style->buildUri($placeholder_image_uri);
if (!file_exists($placeholder_image_uri_with_style)) {
$style->createDerivative($placeholder_image_uri, $placeholder_image_uri_with_style);
}
// Encode the image in base64 to speed up loading times.
$img_binary = fread(fopen($placeholder_image_uri_with_style, "r"), filesize($placeholder_image_uri_with_style));
$file_type = mime_content_type($placeholder_image_uri_with_style);
$img_base64 = 'data:' . $file_type . ';base64,' . base64_encode($img_binary);
$image_uri = file_url_transform_relative(file_create_url($image_uri));
$variables['image'] = [
'#theme' => 'image',
'#uri' => $img_base64,
'#attributes' => [
'class' => ['b-lazy'],
'data-src' => $image_uri,
'width' => $variables['width'],
'height' => $variables['height'],
'title' => !empty($variables['title']) ? $variables['title'] : NULL,
'alt' => !empty($variables['alt']) ? $variables['alt'] : NULL,
],
];
}
