Skip to content

Instantly share code, notes, and snippets.

@chindit
Last active February 14, 2021 18:05
Show Gist options
  • Save chindit/1073476561cad2eec481ca77b4ef9c85 to your computer and use it in GitHub Desktop.
Save chindit/1073476561cad2eec481ca77b4ef9c85 to your computer and use it in GitHub Desktop.
FilePath to GD resource
<?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