- $adjustedPath = $this->storage->adjustPathForDisk($path, $type);
- $disk->put($adjustedPath, $imageData);
- }
-
-
- /**
- * Checks if the image is a gif. Returns true if it is, else false.
- */
- protected function isGif(Image $image): bool
- {
- return strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'gif';
- }
-
- /**
- * Check if the given image and image data is apng.
- */
- protected function isApngData(Image $image, string &$imageData): bool
- {
- $isPng = strtolower(pathinfo($image->path, PATHINFO_EXTENSION)) === 'png';
- if (!$isPng) {
- return false;
- }
-
- $initialHeader = substr($imageData, 0, strpos($imageData, 'IDAT'));
-
- return str_contains($initialHeader, 'acTL');
- }
-
- /**
- * Get the thumbnail for an image.
- * If $keepRatio is true only the width will be used.
- * Checks the cache then storage to avoid creating / accessing the filesystem on every check.
- *
- * @throws Exception
- */
- public function getThumbnail(
- Image $image,
- ?int $width,
- ?int $height,
- bool $keepRatio = false,
- bool $shouldCreate = false,
- bool $canCreate = false,
- ): ?string {
- // Do not resize GIF images where we're not cropping
- if ($keepRatio && $this->isGif($image)) {
- return $this->storage->getPublicUrl($image->path);
- }
-
- $thumbDirName = '/' . ($keepRatio ? 'scaled-' : 'thumbs-') . $width . '-' . $height . '/';
- $imagePath = $image->path;
- $thumbFilePath = dirname($imagePath) . $thumbDirName . basename($imagePath);
-
- $thumbCacheKey = 'images::' . $image->id . '::' . $thumbFilePath;
-
- // Return path if in cache
- $cachedThumbPath = $this->cache->get($thumbCacheKey);
- if ($cachedThumbPath && !$shouldCreate) {
- return $this->storage->getPublicUrl($cachedThumbPath);
- }
-
- // If thumbnail has already been generated, serve that and cache path
- $disk = $this->storage->getDisk($image->type);
- if (!$shouldCreate && $disk->exists($this->storage->adjustPathForDisk($thumbFilePath, $image->type))) {
- $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
-
- return $this->storage->getPublicUrl($thumbFilePath);
- }
-
- $imageData = $disk->get($this->storage->adjustPathForDisk($imagePath, $image->type));
-
- // Do not resize apng images where we're not cropping
- if ($keepRatio && $this->isApngData($image, $imageData)) {
- $this->cache->put($thumbCacheKey, $image->path, 60 * 60 * 72);
-
- return $this->storage->getPublicUrl($image->path);
- }
-
- if (!$shouldCreate && !$canCreate) {
- return null;
- }
-
- // If not in cache and thumbnail does not exist, generate thumb and cache path
- $thumbData = $this->resizeImage($imageData, $width, $height, $keepRatio);
- $this->storage->storeInPublicSpace($disk, $this->storage->adjustPathForDisk($thumbFilePath, $image->type), $thumbData);
- $this->cache->put($thumbCacheKey, $thumbFilePath, 60 * 60 * 72);
-
- return $this->storage->getPublicUrl($thumbFilePath);