Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/GD - Finding Image Resource Type

Having only a valid GD image resource is it possible to find out the type of the original image?

For instance:

$image = ImageCreateFromPNG('http://sstatic.net/so/img/logo.png');

Can I get the original image type (PNG) having only the $image variable available?

like image 201
Alix Axel Avatar asked Dec 27 '09 10:12

Alix Axel


1 Answers

I am not sure if it can be done from the $image variable, but to get the MimeType, you can usually use any of the four:

// with GD
$img = getimagesize($path);
return $img['mime'];

// with FileInfo
$fi = new finfo(FILEINFO_MIME);
return $fi->file($path);

// with Exif (returns image constant value)
return exif_imagetype($path)

// deprecated
return mime_content_type($path);

From your question description I take you want to use a remote file, so you could do something like this to make this work:

$tmpfname = tempnam("/tmp", "IMG_"); // use any path writable for you
$imageCopy = file_get_contents('http://www.example.com/image.png');
file_put_contents($tmpfname, $imageCopy);
$mimetype = // call any of the above functions on $tmpfname;
unlink($tmpfname);

Note: if the MimeType function you will use supports remote files, use it directly, instead of creating a copy of the file first

If you need the MimeType just to determine which imagecreatefrom function to use, why not load the file as a string first and then let GD decide, e.g.

// returns GD image resource of false
$imageString = file_get_contents('http://www.example.com/image.png');
if($imageString !== FALSE) {
    $image = imagecreatefromstring($imageString);
}
like image 199
Gordon Avatar answered Sep 19 '22 23:09

Gordon