ncr*_*ins 2 php image-processing
使用预先构建的系统来抓取远程图像并将其保存到服务器.
目前没有检查图像是否确实存在于该远程位置,并且它具有某种文件类型(jpg,jpeg,gif),并且我的任务是同时执行这两种操作.
我认为这非常简单,因为我只使用一个简单的正则表达式和getimagesize($ image):
$remoteImageURL = 'http://www.exampledomain.com/images/image.jpg';
if(@getimagesize($remoteImageURL) && preg_match("/.(jpg|gif|jpeg)$/", $remoteImageURL) )
{
// insert the image yadda yadda.
}
Run Code Online (Sandbox Code Playgroud)
当我对我正在抓取图像的URL没有任何控制权时会出现问题,例如:
http://www.exampledomain.com/images/2?num=1
所以当谈到这一点时,正则表达式和getimagesize()都会失败,有没有更好的方法呢?
Gor*_*don 12
你可以做到
$headers = get_headers( 'http://www.exampledomain.com/images/2?num=1' );
Run Code Online (Sandbox Code Playgroud)
然后$headers变量将包含类似的内容
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Thu, 14 Oct 2010 09:46:18 GMT
[2] => Server: Apache/2.2
[3] => Last-Modified: Sat, 07 Feb 2009 16:31:04 GMT
[4] => ETag: "340011c-3614-46256a9e66200"
[5] => Accept-Ranges: bytes
[6] => Content-Length: 13844
[7] => Vary: User-Agent
[8] => Expires: Thu, 15 Apr 2020 20:00:00 GMT
[9] => Connection: close
[10] => Content-Type: image/png
)
Run Code Online (Sandbox Code Playgroud)
这将告诉您资源是否存在以及它是什么内容类型(不一定也是图像类型).
根据Pekka的评论编辑,你仍然可能想要在下载后确定它的mime类型.看到
一些给定的方法也适用于远程文件,因此您可以get_headers完全跳过预检.自己决定哪一个适合您的需求.