用PHP保存远程图像

时间:2011-02-11 11:13:09

标签: php

以下代码检索图像并将其保存到本地文件夹。 jpg文件确实保存到本地磁盘,文件大小约为40KB(看起来是正确的)。当我将本地路径放在img标记中时,文件不会显示。

Firebug> Inspect Element显示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,因为如果是块逻辑,那么该变量不会被违反。” - 错了,那个代码确实运行了!

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

1 个答案:

答案 0 :(得分: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');
}