3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
7 use GuzzleHttp\Psr7\Utils;
8 use Illuminate\Support\Facades\Cache;
9 use Intervention\Image\Gd\Driver;
10 use Intervention\Image\Image as InterventionImage;
14 protected const THUMBNAIL_CACHE_TIME = 604_800; // 1 week
16 public function __construct(
17 protected ImageStorage $storage,
22 * Load gallery thumbnails for a set of images.
23 * @param iterable<Image> $images
25 public function loadGalleryThumbnailsForMany(iterable $images, bool $shouldCreate = false): void
27 foreach ($images as $image) {
28 $this->loadGalleryThumbnailsForImage($image, $shouldCreate);
33 * Load gallery thumbnails into the given image instance.
35 public function loadGalleryThumbnailsForImage(Image $image, bool $shouldCreate): void
37 $thumbs = ['gallery' => null, 'display' => null];
40 $thumbs['gallery'] = $this->resizeToThumbnailUrl($image, 150, 150, false, $shouldCreate);
41 $thumbs['display'] = $this->resizeToThumbnailUrl($image, 1680, null, true, $shouldCreate);
42 } catch (Exception $exception) {
43 // Prevent thumbnail errors from stopping execution
46 $image->setAttribute('thumbs', $thumbs);
50 * Get the thumbnail for an image.
51 * If $keepRatio is true only the width will be used.
52 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
56 public function resizeToThumbnailUrl(
60 bool $keepRatio = false,
61 bool $shouldCreate = false
63 // Do not resize GIF images where we're not cropping
64 if ($keepRatio && $this->isGif($image)) {
65 return $this->storage->getPublicUrl($image->path);
68 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
69 $imagePath = $image->path;
70 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
72 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
74 // Return path if in cache
75 $cachedThumbPath = Cache::get($thumbCacheKey);
76 if ($cachedThumbPath && !$shouldCreate) {
77 return $this->storage->getPublicUrl($cachedThumbPath);
80 // If thumbnail has already been generated, serve that and cache path
81 $disk = $this->storage->getDisk($image->type);
82 if (!$shouldCreate && $disk->exists($thumbFilePath)) {
83 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
85 return $this->storage->getPublicUrl($thumbFilePath);
88 $imageData = $disk->get($imagePath);
90 // Do not resize apng images where we're not cropping
91 if ($keepRatio && $this->isApngData($image, $imageData)) {
92 Cache::put($thumbCacheKey, $image->path, static::THUMBNAIL_CACHE_TIME);
94 return $this->storage->getPublicUrl($image->path);
97 // If not in cache and thumbnail does not exist, generate thumb and cache path
98 $thumbData = $this->resizeImageData($imageData, $width, $height, $keepRatio);
99 $disk->put($thumbFilePath, $thumbData, true);
100 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
102 return $this->storage->getPublicUrl($thumbFilePath);
106 * Resize the image of given data to the specified size, and return the new image data.
107 * Format will remain the same as the input format, unless specified.
109 * @throws ImageUploadException
111 public function resizeImageData(
116 ?string $format = null,
119 $thumb = $this->interventionFromImageData($imageData);
120 } catch (Exception $e) {
121 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
124 $this->orientImageToOriginalExif($thumb, $imageData);
127 $thumb->resize($width, $height, function ($constraint) {
128 $constraint->aspectRatio();
129 $constraint->upsize();
132 $thumb->fit($width, $height);
135 $thumbData = (string) $thumb->encode($format);
137 // Use original image data if we're keeping the ratio
138 // and the resizing does not save any space.
139 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
147 * Create an intervention image instance from the given image data.
148 * Performs some manual library usage to ensure image is specifically loaded
149 * from given binary data instead of data being misinterpreted.
151 protected function interventionFromImageData(string $imageData): InterventionImage
153 $driver = new Driver();
154 return $driver->decoder->initFromBinary($imageData);
158 * Orientate the given intervention image based upon the given original image data.
159 * Intervention does have an `orientate` method but the exif data it needs is lost before it
160 * can be used (At least when created using binary string data) so we need to do some
161 * implementation on our side to use the original image data.
162 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
163 * Copyright (c) Oliver Vogel, MIT License.
165 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
167 if (!extension_loaded('exif')) {
171 $stream = Utils::streamFor($originalData)->detach();
172 $exif = @exif_read_data($stream);
173 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
175 switch ($orientation) {
183 $image->rotate(180)->flip();
186 $image->rotate(270)->flip();
192 $image->rotate(90)->flip();
201 * Checks if the image is a gif. Returns true if it is, else false.
203 protected function isGif(Image $image): bool
205 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
209 * Check if the given image and image data is apng.
211 protected function isApngData(Image $image, string &$imageData): bool
213 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
218 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
220 return str_contains($initialHeader, 'acTL');