Base64ImageFormatter.php in Entity Print 8.2
File
src/Plugin/Field/FieldFormatter/Base64ImageFormatter.php
View source
<?php
namespace Drupal\entity_print\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\Plugin\Field\FieldFormatter\ImageFormatter;
class Base64ImageFormatter extends ImageFormatter {
public static function defaultSettings() {
return [
'image_style' => '',
];
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['image_style'] = [
'#title' => $this
->t('Image style'),
'#type' => 'select',
'#default_value' => $this
->getSetting('image_style'),
'#empty_option' => $this
->t('None (original image)'),
'#options' => image_style_options(FALSE),
];
return $element;
}
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
$file = $item->entity;
$uri = $file
->getFileUri();
if ($this
->getSetting('image_style')) {
$image_style = ImageStyle::load($this
->getSetting('image_style'));
$uri = $this
->getImageStyleUri($image_style, $file) ?: $uri;
}
$base_64_image = base64_encode(file_get_contents($uri));
$filemime = $file
->getMimeType();
$element[$delta] = [
'#theme' => 'image',
'#uri' => "data:{$filemime};charset=utf-8;base64,{$base_64_image}",
];
}
return $element;
}
protected function getImageStyleUri(ImageStyle $image_style, File $file) {
$file_uri = $file
->getFileUri();
$image_style_uri = $image_style
->buildUri($file_uri);
if (file_exists($image_style_uri) || $image_style
->createDerivative($file_uri, $image_style_uri)) {
return $image_style_uri;
}
return FALSE;
}
}