3 namespace BookStack\Uploads;
5 use BookStack\Exceptions\ImageUploadException;
7 use GuzzleHttp\Psr7\Utils;
8 use Illuminate\Support\Facades\Cache;
9 use Intervention\Image\Decoders\BinaryImageDecoder;
10 use Intervention\Image\Drivers\Gd\Decoders\NativeObjectDecoder;
11 use Intervention\Image\Drivers\Gd\Driver;
12 use Intervention\Image\Encoders\AutoEncoder;
13 use Intervention\Image\Encoders\PngEncoder;
14 use Intervention\Image\Interfaces\ImageInterface as InterventionImage;
15 use Intervention\Image\ImageManager;
16 use Intervention\Image\Origin;
20 protected const THUMBNAIL_CACHE_TIME = 604_800; // 1 week
22 public function __construct(
23 protected ImageStorage $storage,
28 * Load gallery thumbnails for a set of images.
29 * @param iterable<Image> $images
31 public function loadGalleryThumbnailsForMany(iterable $images, bool $shouldCreate = false): void
33 foreach ($images as $image) {
34 $this->loadGalleryThumbnailsForImage($image, $shouldCreate);
39 * Load gallery thumbnails into the given image instance.
41 public function loadGalleryThumbnailsForImage(Image $image, bool $shouldCreate): void
43 $thumbs = ['gallery' => null, 'display' => null];
46 $thumbs['gallery'] = $this->resizeToThumbnailUrl($image, 150, 150, false, $shouldCreate);
47 $thumbs['display'] = $this->resizeToThumbnailUrl($image, 1680, null, true, $shouldCreate);
48 } catch (Exception $exception) {
49 // Prevent thumbnail errors from stopping execution
52 $image->setAttribute('thumbs', $thumbs);
56 * Get the thumbnail for an image.
57 * If $keepRatio is true only the width will be used.
58 * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
62 public function resizeToThumbnailUrl(
66 bool $keepRatio = false,
67 bool $shouldCreate = false
69 // Do not resize GIF images where we're not cropping
70 if ($keepRatio && $this->isGif($image)) {
71 return $this->storage->getPublicUrl($image->path);
74 $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
75 $imagePath = $image->path;
76 $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
78 $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
80 // Return path if in cache
81 $cachedThumbPath = Cache::get($thumbCacheKey);
82 if ($cachedThumbPath && !$shouldCreate) {
83 return $this->storage->getPublicUrl($cachedThumbPath);
86 // If thumbnail has already been generated, serve that and cache path
87 $disk = $this->storage->getDisk($image->type);
88 if (!$shouldCreate && $disk->exists($thumbFilePath)) {
89 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
91 return $this->storage->getPublicUrl($thumbFilePath);
94 $imageData = $disk->get($imagePath);
96 // Do not resize apng images where we're not cropping
97 if ($keepRatio && $this->isApngData($image, $imageData)) {
98 Cache::put($thumbCacheKey, $image->path, static::THUMBNAIL_CACHE_TIME);
100 return $this->storage->getPublicUrl($image->path);
103 // If not in cache and thumbnail does not exist, generate thumb and cache path
104 $thumbData = $this->resizeImageData($imageData, $width, $height, $keepRatio, $this->getExtension($image));
105 $disk->put($thumbFilePath, $thumbData, true);
106 Cache::put($thumbCacheKey, $thumbFilePath, static::THUMBNAIL_CACHE_TIME);
108 return $this->storage->getPublicUrl($thumbFilePath);
112 * Resize the image of given data to the specified size, and return the new image data.
113 * Format will remain the same as the input format, unless specified.
115 * @throws ImageUploadException
117 public function resizeImageData(
122 ?string $format = null,
125 $thumb = $this->interventionFromImageData($imageData, $format);
126 } catch (Exception $e) {
127 throw new ImageUploadException(trans('errors.cannot_create_thumbs'));
130 $this->orientImageToOriginalExif($thumb, $imageData);
133 $thumb->scaleDown($width, $height);
135 $thumb->cover($width, $height);
138 $encoder = match ($format) {
139 'png' => new PngEncoder(),
140 default => new AutoEncoder(),
143 $thumbData = (string) $thumb->encode($encoder);
145 // Use original image data if we're keeping the ratio
146 // and the resizing does not save any space.
147 if ($keepRatio && strlen($thumbData) > strlen($imageData)) {
155 * Create an intervention image instance from the given image data.
156 * Performs some manual library usage to ensure image is specifically loaded
157 * from given binary data instead of data being misinterpreted.
159 protected function interventionFromImageData(string $imageData, ?string $fileType): InterventionImage
161 $manager = new ImageManager(
163 autoOrientation: false,
166 // Ensure gif images are decoded natively instead of deferring to intervention GIF
167 // handling since we don't need the added animation support.
168 $isGif = $fileType === 'gif';
169 $decoder = $isGif ? NativeObjectDecoder::class : BinaryImageDecoder::class;
170 $input = $isGif ? @imagecreatefromstring($imageData) : $imageData;
172 $image = $manager->read($input, $decoder);
175 $image->setOrigin(new Origin('image/gif'));
182 * Orientate the given intervention image based upon the given original image data.
183 * Intervention does have an `orientate` method but the exif data it needs is lost before it
184 * can be used (At least when created using binary string data) so we need to do some
185 * implementation on our side to use the original image data.
186 * Bulk of logic taken from: https://github.com/Intervention/image/blob/b734a4988b2148e7d10364b0609978a88d277536/src/Intervention/Image/Commands/OrientateCommand.php
187 * Copyright (c) Oliver Vogel, MIT License.
189 protected function orientImageToOriginalExif(InterventionImage $image, string $originalData): void
191 if (!extension_loaded('exif')) {
195 $stream = Utils::streamFor($originalData)->detach();
196 $exif = @exif_read_data($stream);
197 $orientation = $exif ? ($exif['Orientation'] ?? null) : null;
199 switch ($orientation) {
207 $image->rotate(180)->flip();
210 $image->rotate(270)->flip();
216 $image->rotate(90)->flip();
225 * Checks if the image is a gif. Returns true if it is, else false.
227 protected function isGif(Image $image): bool
229 return $this->getExtension($image) === 'gif';
233 * Get the extension for the given image, normalised to lower-case.
235 protected function getExtension(Image $image): string
237 return strtolower(pathinfo($image->path, PATHINFO_EXTENSION));
241 * Check if the given image and image data is apng.
243 protected function isApngData(Image $image, string &$imageData): bool
245 $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
250 $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
252 return str_contains($initialHeader, 'acTL');