image: throw proper errors in decodable (close #529)

Signed-off-by: Varun Patil <varunpatil@ucla.edu>
pull/563/head
Varun Patil 2023-03-29 15:05:05 -07:00
parent 687cafb13d
commit abfe0cf94d
1 changed files with 38 additions and 6 deletions

View File

@ -260,12 +260,7 @@ class ImageController extends GenericApiController
// Convert image to JPEG if required // Convert image to JPEG if required
if (!\in_array($mimetype, ['image/png', 'image/webp', 'image/jpeg', 'image/gif'], true)) { if (!\in_array($mimetype, ['image/png', 'image/webp', 'image/jpeg', 'image/gif'], true)) {
$image = new \Imagick(); [$blob, $mimetype] = $this->getImageJPEG($blob, $mimetype);
$image->readImageBlob($blob);
$image->setImageFormat('jpeg');
$image->setImageCompressionQuality(95);
$blob = $image->getImageBlob();
$mimetype = $image->getImageMimeType();
} }
// Return the image // Return the image
@ -276,6 +271,43 @@ class ImageController extends GenericApiController
}); });
} }
/**
* Given a blob of image data, return a JPEG blob.
*
* @param string $blob Blob of image data in any format
* @param string $mimetype Mimetype of image data
*
* @return array [blob, mimetype]
*/
private function getImageJPEG($blob, $mimetype): array {
// TODO: Use imaginary if available
// Check if Imagick is available
if (!\class_exists('Imagick')) {
throw Exceptions::Forbidden('Imagick extension is not available');
}
// Read original image
try {
$image = new \Imagick();
$image->readImageBlob($blob);
} catch (\ImagickException $e) {
throw Exceptions::Forbidden('Imagick failed to read image: '. $e->getMessage());
}
// Convert to JPEG
try {
$image->setImageFormat('jpeg');
$image->setImageCompressionQuality(95);
$blob = $image->getImageBlob();
$mimetype = $image->getImageMimeType();
} catch (\ImagickException $e) {
throw Exceptions::Forbidden('Imagick failed to convert image: '. $e->getMessage());
}
return [$blob, $mimetype];
}
/** /**
* Get the tags for a file. * Get the tags for a file.
*/ */