如何从PHP中的301重定向下载链接获取图像?

时间:2011-09-25 22:23:31

标签: php image curl download gd

我正在尝试使用PHP下载this图像以使用GD进行编辑。我找到了许多图像链接解决方案,但这个是下载链接。

编辑:

$curl = curl_init("http://minecraft.net/skin/Notch.png");
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefromstring($bin);

这是我目前的代码。它显示“301 Moved Permanently”。我必须设置CURLOPT吗?

3 个答案:

答案 0 :(得分:6)

$curl = curl_init("http://minecraft.net/skin/Notch.png");
// Moved? Fear not, we'll chase it!
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Because you want the result as a string
curl_setopt($curl,  CURLOPT_RETURNTRANSFER, true); 
$bin = curl_exec($curl);
curl_close($curl);
$img = @imagecreatefromstring($bin);

答案 1 :(得分:0)

这是一个直接将图像保存到文件(而不是使用imagecreatefromstring)的选项:

<?php
$fileName = '/some/local/path/image.jpg';
$fileUrl  = 'http://remote.server/download/link';
$ch = curl_init($fileUrl); // set the url to open and download
$fp = fopen($fileName, 'wb'); // open the local file pointer to save downloaded image
curl_setopt($ch, CURLOPT_FILE, $fp); // tell curl to save to the file pointer
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // tell curl to follow 30x redirects
curl_exec($ch); // fetch the image and save it with curl
curl_close($ch); // close curl
fclose($fp); // close the local file pointer

答案 2 :(得分:-1)

fopen - 如果允许url fopen,则取决于你的php设置。

curl

请参阅精美的php手册。