问题
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?
回答1:
I don't think so, no. $image is in GD's internal image format after it has been processed by the ImageCreate()
function.
回答2:
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);
}
回答3:
You could just try loading the resource with the png loader, and if it's not a png image, it will fail, returning FALSE. Then just repeat with each of the valid formats you want to have, and if all fail, then display an error.
来源:https://stackoverflow.com/questions/1965689/php-gd-finding-image-resource-type