短版本当我尝试使用此链接运行file_get_contents()时,'http://s1.reutersmedia.net/resources/r/?m=02&d=20131205&t=2&i=817503382&w=&fh=&fw=&ll=700&pl=378&r=CBRE9B401AG00',返回:"非法:d-msg"。为什么file_get_contents()在大多数图像链接上都有效,而在这个链接上却无效,我该如何使它有效?
详细信息我的网络应用程序的部分功能是解析外部html文件中的图像,然后允许用户选择所需的图像,并自动将图像的缩小版本保存到我的服务器。我的代码适用于99%的情况,但对于剩下的1%,我无法成功地将图像文件放到我的服务器上以重新调整其大小。不起作用的情况似乎都涉及具有"src"属性的html元素,如下所示:
http://s1.reutersmedia.net/resources/r/?m=02&d=20131205&t=2&i=817503382&w=&fh=&fw=&ll=580&pl=378&r=CBRE9B401AG00
与更标准的图像路径相反,例如
http://www.wired.com/images_blogs/wiredscience/2013/12/keyes-wd.jpg
以下是我用来在用户选择外部图像后获取和保存外部图像的代码,其中变量$newFileName等于img路径字符串,例如上面粘贴的字符串:
$contentOrFalseOnFailure = file_get_contents($newFileName);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
$fileName = basename($newFileName);
$fileTmpLoc = $filenameOut;
$fileSize = $byteCountOrFalseOnFailure;
$fileExt = pathinfo($fileTmpLoc, PATHINFO_EXTENSION);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
当src是非标准的时,脚本不会超过这一点,即我得到"That image has no dimestions"错误。如何保存保存这些非标准图像?
如果您只对图像尺寸感兴趣,而不关心其他方面,您可以使用GD的imagecreatefromstring(),而不需要磁盘上的临时文件:
$img = file_get_contents($url);
$gd = imagecreatefromstring($img);
$width = imagesx($gd);
$height = imagesy($gd);
然而,这样做的缺点是必须将图像解压缩到内存中。您必须希望远程服务器在解压缩时不会发送一个大小不合理的图像,该图像不会超过PHP内存限制。
忽略URL,查看响应中的Content-Type
标头。