2016-01-26 30 views
0

我使用来自第三方网站的API制作缩略图图像并在我的网站上显示。我在php中使用以下行显示缩略图:将图像下载到由API获取的服务器上

echo '<img src="http://api.thirdpartysite.org/?some_param" />'; 

它工作正常,图像在浏览器中完美显示。当然,从我的浏览器我可以保存法师到我的电脑。

有没有一种方法可以直接将图像文件直接下载到我的服务器使用PHP?

编辑: 我已经尝试过

file_put_contents("image.png", fopen("http://api.thirdpartysite.org/?some_param'", 'r')); 

,并在服务器

我使用的主机共享,Linux服务器创建一个空的图像文件。

+0

你必须使用:'file_put_contents (“image.png”,file_get_contents(“http://api.thirdpartysite.org/?some_param'”));'。 'fopen()'函数可以是更好的方法,但是有一个[不同的语法](http://nl3.php.net/manual/en/function.fread.php)。 – fusion3k

+0

谢谢。它仍然会创建一个空文件,只是第三方网站的水印。 – cybergeek654

+0

这是因为第三方网站可能不允许直接下载!这是一个复杂的问题,取决于第三方网站,它检查HTTP-REFERER,更复杂的cookie。 – fusion3k

回答

0

我使用了curl_exec(),它像一个魅力一样工作。

0

伟大的细微差别是,你可能不知道下载的图像文件的扩展名。
所以目前我可以建议你一个简单的解决方案,下载当前的谷歌标志图像(例如)。
的功能列表,我们将使用: file_get_contentsfile_put_contentsgetimagesizerenameheaderreadfile

$img = file_get_contents("https://www.google.com.ua/logos/doodles/2016/90th-anniversary-of-the-first-demonstration-of-television-6281357497991168.3-res.png"); 
file_put_contents("image", $img); // assuming that we don't know the extension at the moment 
$image_data = getimagesize("image"); // getting image details 
$ext = explode('/',$image_data['mime'])[1]; // getting image mime type 
rename("image", "image." . $ext); // rename image specifying determined extension 

// the immediate test: we will immediately output the downloaded image (just for testing) 
header("Content-Type: image/" . $ext); 
readfile("image." . $ext); 

和输出将如下面所示:
enter image description here

相关问题