rickypai
rickypai

Reputation: 4016

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

Upvotes: 7

Views: 5831

Answers (3)

oucil
oucil

Reputation: 4554

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

Upvotes: 7

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);
    }
}

Upvotes: 1

AndrewR
AndrewR

Reputation: 6748

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);

Upvotes: 12

Related Questions