Check if the string is an image

There is an image in a string format, the output of this line with some headers of the mime type will be enough to display it on the page, how can I check if this line is an image?

+5
source share
1 answer

"The image resource will be returned upon successful completion. FALSE is returned if the image type is not supported, the data is not in the recognized format, or the image is damaged 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.';
}
?>

http://php.net/manual/en/function.imagecreatefromstring.php

+9
source

All Articles