Last active
February 14, 2021 18:05
-
-
Save chindit/1073476561cad2eec481ca77b4ef9c85 to your computer and use it in GitHub Desktop.
FilePath to GD resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
final class ImageFactory | |
{ | |
public static function getResource(string $filePath): \GdImage | |
{ | |
if (!is_file($filePath)) { | |
throw new IOException('File «' . $filePath . '» was not found'); | |
} | |
$imageType = exif_imagetype($filePath); | |
if ($imageType === false) { | |
throw new IOException('File «' . $filePath . '» is not a picture'); | |
} | |
$resource = match ($imageType) { | |
IMAGETYPE_GIF => imagecreatefromgif($filePath), | |
IMAGETYPE_JPEG => imagecreatefromjpeg($filePath), | |
IMAGETYPE_PNG => imagecreatefrompng($filePath), | |
IMAGETYPE_WBMP => imagecreatefromwbmp($filePath), | |
IMAGETYPE_XBM => imagecreatefromxbm($filePath), | |
default => false, | |
}; | |
if ($resource === false) { | |
throw new UnsupportedMediaTypeException(sprintf('Picture of type %s is not supported', $imageType)); | |
} | |
return $resource; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment