如何使用PHP从缺少图像扩展的远程服务器保存图像


How to save image from remote server where image extension is missed using PHP

我使用DOMDocument提取包含图像文件的html页面,html页面看起来像这个

<div>
   <img src="http://pic.aa.com/a/b/0525">
</div>

在我提取src地址后,我把它放在这个函数中

copy('http://pic.aa.com/a/b/0525', 'd:tmp/img_name');

我不知道如何决定文件的扩展名,从uri中没有任何线索,唯一可能的方法是使用chrome浏览器工具检查响应头,但似乎缺乏效率,有人知道正确的方法吗?

我可以给你提示使用这里提供的exif_imagetype();函数:

http://php.net/manual/en/function.exif-imagetype.php

您可以使用for/while/foreach循环来确定图像类型,如:

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
    echo 'The picture is not a gif';
}
?>

类似这样的东西也可能帮助你:

<?php 
$filename = 'http://myhost/myunkownimagefiletype'; 
$size = getimagesize($filename); 
switch ($size['mime']) { 
    case "image/gif": 
        echo "Image is a gif"; 
        break; 
    case "image/jpeg": 
        echo "Image is a jpeg"; 
        break; 
    case "image/png": 
        echo "Image is a png"; 
        break; 
    case "image/bmp": 
        echo "Image is a bmp"; 
        break; 
} 
?>