2011-02-11 65 views
1

以下代码检索图像并将其保存到本地文件夹。一个jpg文件确实保存在本地磁盘上,文件大小约为40KB(似乎是正确的)。当我把本地路径放在img标签中时,文件不会显示。用php保存远程图像

Firebug>检查元素显示大小为0 X 0,并且我无法在保存到桌面时查看图像。

file_put_contents,file_get_contents和getimagesize不返回FAIL。 $ url是一个有效的图像。问题只是在本地保存,文件似乎已损坏 - 怎么回事?

$url = $image->request_url; //the image generated on the remote server 
    //print_r(getimagesize($url)); die; 
    $img = 'thumbalizr/cache/screenshot_' . $row['id'] . '.jpg'; //path to our local cache folder + unique filename 
    if(!$captured_file = file_get_contents($url)) die('file could not be retrieved'); 
    elseif(!file_put_contents($img, $captured_file, FILE_APPEND)) die('file could not be written to local disk'); //write the image to our local cache 

“你确定路径正确吗?你试过绝对路径吗?”是的

“您是否检查过图片是否正确下载,可能是使用其他工具(例如ftp,diff)?”我可以通过ftp下载img,但它也不能在本地计算机上打开。

“如果您直接在浏览器中调用URL,您会得到什么?” FF刚刚打印出的URL,而不是显示

形象“你为什么要使用FILE_APPEND?如果目标已经存在,这种写入结束,这自然就会给你一个损坏的映像”我删除FILE_APPEND,没有什么区别

“来源和最终延期是一样的吗?”是的,我尝试使用jpg,jpeg和png - 没有区别

“首先,示例代码是错误的。不能在file_put_content中使用$ capture_file,因为如果块逻辑,该变量没有被拒绝。 - 错误,代码确实运行!

“你可以看看图像文件” - 不!虽然该文件具有实际的文件大小,我可以下载它,但无法打开它。

+0

您应该发布您正在使用的html来查看图像。你确定路径是正确的吗?你试过绝对路径吗?您是否检查过图片是否正确下载,可能是使用其他实用程序(例如ftp,diff)? – Benubird 2011-02-11 11:16:07

回答

0

首先在文本编辑器中检查您正在下载的文件,看看您是否获取HTML错误页面而不是二进制图像数据。

其次,我会使用curl,因为它提供了更好的成功/错误信息。这里是你的例子修改使用它。

//path to our local cache folder + unique filename 
$img_path = 'thumbalizr/cache/screenshot_' . $row['id'] . '.jpg'; 

$c = curl_init(); 
curl_setopt($c, CURLOPT_URL, $image->request_url); 
curl_setopt($c, CURLOPT_HEADER, 0); 
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30); 
curl_setopt($c, CURLOPT_AUTOREFERER, true); 
curl_setopt($c, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($c, CURLOPT_FORBID_REUSE, true); 
// curl can automatically write the file out for you 
curl_setopt($c, CURLOPT_FILE, $img_path); 

// You can get more elaborate success/error info from 
// curl_getinfo() http://www.php.net/manual/en/function.curl-getinfo.php 
if (!curl_exec($c)) { 
    die('file could not be retrieved'); 
}