Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if string is image

Tags:

php

image

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?

like image 820
Timo Huovinen Avatar asked May 19 '12 08:05

Timo Huovinen


1 Answers

"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.';
}
?>

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

like image 72
josmith Avatar answered Sep 28 '22 04:09

josmith