【问题标题】:How can get an image from a 301 redirect download link in PHP?如何从 PHP 中的 301 重定向下载链接获取图像?
【发布时间】:2011-09-25 22:23:31
【问题描述】:

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

编辑:

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

这是我当前的代码。它显示“301 永久移动”。我必须设置 CURLOPT 吗?

【问题讨论】:

  • 下载链接和图片链接没有区别。

标签: php image curl download gd


【解决方案1】:
$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);

【讨论】:

    【解决方案2】:

    这里是直接将图像保存到文件的选项(而不是使用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
    

    【讨论】:

      【解决方案3】:

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

      curl

      请参阅精美的 php 手册。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-29
        • 2020-10-01
        • 1970-01-01
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多