3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
7 use GuzzleHttp\Psr7\Utils;
8 use Illuminate\Support\Facades\Cache;
9 use Intervention\Image\Image as InterventionImage;
10 use Intervention\Image\ImageManager;
14 protected const THUMBNAIL_CACHE_TIME = 604_800; // 1 week
16 public function __construct(
17 protected ImageManager $intervention,
18 protected ImageStorage $storage,
23 * Load gallery thumbnails for a set of images.
24 * @param iterable<Image> $images
26 public function loadGalleryThumbnailsForMany(iterable $images, bool $shouldCreate = false): void
28 foreach ($images as $image) {
29 $this->loadGalleryThumbnailsForImage($image, $shouldCreate);
34 * Load gallery thumbnails into the given image instance.
36 public function loadGalleryThumbnailsForImage(Image $image, bool $shouldCreate): void
38 $thumbs = ['gallery' => null, 'display' => null];
41 $thumbs['gallery'] = $this->resizeToThumbnailUrl($image, 150, 150, false, $shouldCreate);
42 $thumbs['display'] = $this->resizeToThumbnailUrl($image, 1680, null, true, $shouldCreate);
43 } catch (Exception $exception) {
44 // Prevent thumbnail errors from stopping execution
47 $image->setAttribute('thumbs', $thumbs);
51 * Get the thumbnail for an image.
52 * If $keepRatio is true only the width will be used.
53 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
57 public function resizeToThumbnailUrl(
61 bool $keepRatio = false,
62 bool $shouldCreate = false
64 // Do not resize GIF images where we're not cropping
65 if ($keepRatio && $this->isGif($image)) {
66 return $this->storage->getPublicUrl($image->path);
69 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
70 $imagePath = $image->path;
71 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
73 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
75 // Return path if in cache
76 $cachedThumbPath = Cache::get($thumbCacheKey);
77 if ($cachedThumbPath && !$shouldCreate) {
78 return $this->storage->getPublicUrl($cachedThumbPath);
81 // If thumbnail has already been generated, serve that and cache path
82 $disk = $this->storage->getDisk($image->type);
83 if (!$shouldCreate && $disk->exists($thumbFilePath)) {
84 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
86 return $this->storage->getPublicUrl($thumbFilePath);
89 $imageData = $disk->get($imagePath);
91 // Do not resize apng images where we're not cropping
92 if ($keepRatio && $this->isApngData($image, $imageData)) {
93 Cache::put($thumbCacheKey, $image->path, static::THUMBNAIL_CACHE_TIME);
95 return $this->storage->getPublicUrl($image->path);
98 // If not in cache and thumbnail does not exist, generate thumb and cache path
99 $thumbData = $this->resizeImageData($imageData, $width, $height, $keepRatio);
100 $disk->put($thumbFilePath, $thumbData, true);
101 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
103 return $this->storage->getPublicUrl($thumbFilePath);
107 * Resize the image of given data to the specified size, and return the new image data.
108 * Format will remain the same as the input format, unless specified.
110 * @throws ImageUploadException
112 public function resizeImageData(
117 ?string $format = null,
120 $thumb = $this->intervention->make($imageData);
121 } catch (Exception $e) {
122 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
125 $this->orientImageToOriginalExif($thumb, $imageData);
128 $thumb->resize($width, $height, function ($constraint) {
129 $constraint->aspectRatio();
130 $constraint->upsize();
133 $thumb->fit($width, $height);
136 $thumbData = (string) $thumb->encode($format);
138 // Use original image data if we're keeping the ratio
139 // and the resizing does not save any space.
140 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
148 * Orientate the given intervention image based upon the given original image data.
149 * Intervention does have an `orientate` method but the exif data it needs is lost before it
150 * can be used (At least when created using binary string data) so we need to do some
151 * implementation on our side to use the original image data.
152 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
153 * Copyright (c) Oliver Vogel, MIT License.
155 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
157 if (!extension_loaded('exif')) {
161 $stream = Utils::streamFor($originalData)->detach();
162 $exif = @exif_read_data($stream);
163 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
165 switch ($orientation) {
173 $image->rotate(180)->flip();
176 $image->rotate(270)->flip();
182 $image->rotate(90)->flip();
191 * Checks if the image is a gif. Returns true if it is, else false.
193 protected function isGif(Image $image): bool
195 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
199 * Check if the given image and image data is apng.
201 protected function isApngData(Image $image, string &$imageData): bool
203 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
208 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
210 return str_contains($initialHeader, 'acTL');