upright($this->read($uploadedFilePath), $uploadedFilePath); try { $full = $this->scaled($image, self::MAX_SIZE); $thumbnail = $this->scaled($image, self::THUMBNAIL_SIZE); $name = 'task-images/'.$taskId.'/'.Str::uuid()->toString(); $stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', imagesx($full), imagesy($full)); Storage::disk(self::DISK)->put($stored->path, $this->jpeg($full)); Storage::disk(self::DISK)->put($stored->thumbnailPath, $this->jpeg($thumbnail)); return $stored; } finally { imagedestroy($image); } } public function delete(array $paths): void { if ($paths !== []) { Storage::disk(self::DISK)->delete($paths); } } /** * @throws InvalidTaskImage */ private function read(string $path): GdImage { $info = @getimagesize($path); if ($info === false || $info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) { throw new InvalidTaskImage; } $image = match ($info[2]) { IMAGETYPE_JPEG => @imagecreatefromjpeg($path), IMAGETYPE_PNG => @imagecreatefrompng($path), IMAGETYPE_GIF => @imagecreatefromgif($path), IMAGETYPE_WEBP => @imagecreatefromwebp($path), default => false, }; if ($image === false) { throw new InvalidTaskImage; } // Transparent parts become white, as JPEG has no transparency. $flat = imagecreatetruecolor(imagesx($image), imagesy($image)); imagefill($flat, 0, 0, (int) imagecolorallocate($flat, 255, 255, 255)); imagecopy($flat, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); imagedestroy($image); return $flat; } /** * Phone cameras save photos sideways and tell the right way up in EXIF. */ private function upright(GdImage $image, string $path): GdImage { $exif = function_exists('exif_read_data') ? @exif_read_data($path) : false; $orientation = is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1; $rotated = match ($orientation) { 3 => imagerotate($image, 180, 0), 5, 6 => imagerotate($image, -90, 0), 7, 8 => imagerotate($image, 90, 0), default => $image, }; if ($rotated === false) { return $image; } if (in_array($orientation, [2, 5, 7], true)) { imageflip($rotated, IMG_FLIP_HORIZONTAL); } elseif ($orientation === 4) { imageflip($rotated, IMG_FLIP_VERTICAL); } if ($rotated !== $image) { imagedestroy($image); } return $rotated; } /** * A copy whose longer side is at most the given size. */ private function scaled(GdImage $image, int $maxSize): GdImage { $width = imagesx($image); $height = imagesy($image); $ratio = min(1, $maxSize / max($width, $height)); $newWidth = max(1, (int) round($width * $ratio)); $newHeight = max(1, (int) round($height * $ratio)); $copy = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($copy, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); return $copy; } private function jpeg(GdImage $image): string { ob_start(); imagejpeg($image, null, self::QUALITY); imagedestroy($image); return (string) ob_get_clean(); } }