get($path); if ($contents === null) { throw new RuntimeException("Banner photo {$path} is missing."); } // A 6 MB photo can be very large once opened, so give GD room for this one job. ini_set('memory_limit', '512M'); $image = @imagecreatefromstring($contents); if (! $image instanceof GdImage) { throw new RuntimeException("Banner photo {$path} could not be opened."); } $image = $this->turnUpright($image, $contents); $image = $this->resize($image); ob_start(); imagewebp($image, null, self::QUALITY); $webp = (string) ob_get_clean(); $folder = dirname($path); $newPath = ($folder === '.' ? '' : $folder.'/').'banner-'.Str::random(24).'.webp'; $disk->put($newPath, $webp); return $newPath; } /** * The size the photo will be saved at. * * @return array{0: int, 1: int} */ public static function targetSize(int $width, int $height): array { $scale = min( max(1, self::TARGET_WIDTH / $width), self::MAX_SIDE / max($width, $height), ); return [(int) round($width * $scale), (int) round($height * $scale)]; } private function resize(GdImage $image): GdImage { $width = imagesx($image); $height = imagesy($image); [$newWidth, $newHeight] = self::targetSize($width, $height); if ($newWidth === $width && $newHeight === $height) { return $image; } $resized = imagecreatetruecolor($newWidth, $newHeight); // Keep see-through parts of PNG and WebP photos. imagealphablending($resized, false); imagesavealpha($resized, true); imagefill($resized, 0, 0, imagecolorallocatealpha($resized, 0, 0, 0, 127)); imagecopyresampled($resized, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // Enlarged photos turn a little soft, so sharpen them gently. if ($newWidth > $width * 1.05) { imageconvolution($resized, [[-1, -1, -1], [-1, 20, -1], [-1, -1, -1]], 12, 0); } return $resized; } /** * Phones often save photos sideways with a note saying which way is up. Follow that note. */ private function turnUpright(GdImage $image, string $contents): GdImage { if (! function_exists('exif_read_data') || ! str_starts_with($contents, "\xFF\xD8")) { return $image; } $exif = @exif_read_data('data://image/jpeg;base64,'.base64_encode($contents)); $orientation = is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1; if (in_array($orientation, [2, 4, 5, 7], true)) { imageflip($image, IMG_FLIP_HORIZONTAL); } $angle = match ($orientation) { 3, 4 => 180, 5, 6 => -90, 7, 8 => 90, default => 0, }; if ($angle === 0) { return $image; } $turned = imagerotate($image, $angle, 0); return $turned instanceof GdImage ? $turned : $image; } }