There is an image in string format, outputting that string with some mime type headers would be enough to render it on a page, how to check if that string is an image?
1 Answer
"An image resource will be returned on success. FALSE is returned if the image type is unsupported, the data is not in a recognised format, or the image is corrupt and cannot be loaded."
Example:
<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>
3 Comments
NT_
You need to suppress errors using '@' or else you are doomed for that
imagecreatefromstring() .Timo Huovinen
@ngen Any way to avoid getting doomed and at the same time avoid using @?
NT_
@YuriKolovsky You can't . Since you are trying to load a string into a function which is expecting an image. It will fail 1) if the image data is corrupt . 2) if it's not an image.