| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- <?php
-
- namespace App\StorePlan;
-
- use GdImage;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Support\Str;
- use RuntimeException;
-
- /**
- * Gets an uploaded banner photo ready for a wide hero, so merchants can upload what they have.
- *
- * - Small photos are enlarged to 1600 pixels across and lightly sharpened.
- * - Very large photos are made smaller (longest side 2400), so the store loads fast.
- * - Phone photos are turned the right way up.
- * - Everything is saved as WebP. Saving again also drops hidden details such as the GPS location.
- *
- * Built into PHP (GD), so it costs nothing. An AI upscaler could replace `resize()` later.
- */
- class BannerPhoto
- {
- /** The smallest photo we accept. Enlarging more than about 5 times looks too soft. */
- public const MIN_WIDTH = 300;
-
- public const MIN_HEIGHT = 200;
-
- /** Small photos are enlarged to this width. */
- public const TARGET_WIDTH = 1600;
-
- /** No side is ever longer than this. */
- public const MAX_SIDE = 2400;
-
- public const QUALITY = 82;
-
- /**
- * Prepare the photo at this path on the "public" disk and save it as a new WebP file.
- * Returns the new file's path. The original file is left for the caller to remove.
- */
- public function prepare(string $path): string
- {
- $disk = Storage::disk('public');
- $contents = $disk->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;
- }
- }
|