Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php get image size from a string of image content

I have a function that would fetch a remote image via CURL, returning a string variable of the contents of the remote image.

I do not wish to write the content into the file, but wish to get the size of the image.

since getimagesize() only supports a file, is there a function similar to getimagesize() but can support strings of image content?

to clarify:

$image_content = file_get_contents('http://www.example.com/example.jpg');

how to get the image size of $image_content instead of running getimagesize('http://www.example.com/example.jpg');?

Thanks in advance

like image 881
rickypai Avatar asked Jan 19 '12 05:01

rickypai


3 Answers

PHP functions imagecreatefromstring, imagesx, and imagesy.

Something like this;

$image_content = file_get_contents('http://www.example.com/example.jpg');
$image = imagecreatefromstring($image_content);
$width = imagesx($image);
$height = imagesy($image);
like image 179
AndrewR Avatar answered Oct 09 '22 07:10

AndrewR


FYI, for those coming late to the game, PHP >= 5.4 now includes getimagesizefromstring() which is identical to getimagesize() but accepts a string for the first param instead of a location.

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

like image 21
oucil Avatar answered Oct 09 '22 07:10

oucil


OK, I found answer for PHP 5.3 and less

if (!function_exists('getimagesizefromstring')) {
    function getimagesizefromstring($data)
    {
        $uri = 'data://application/octet-stream;base64,' . base64_encode($data);
        return getimagesize($uri);
    }
}
like image 1
Bjørson Bjørson Avatar answered Oct 09 '22 08:10

Bjørson Bjørson