【问题标题】:Storing an image from a link in PHP从 PHP 中的链接存储图像
【发布时间】:2009-10-19 22:27:28
【问题描述】:

给定一个图像的直接链接,我如何使用 php 将实际图像存储在我在服务器上创建的文件夹中?

谢谢

【问题讨论】:

    标签: php image storage


    【解决方案1】:
    $image_url = 'http://example.com/image.jpg';
    $image = file_get_contents($image_url);
    file_put_contents('/my/path/image.jpg', $image);
    

    简而言之,抓取图像,存储图像.. 就这么简单。

    注意:allow_url_fopen php.ini 设置必须设置为 true 才能使上述示例正常工作。

    【讨论】:

    • 是的,假设在 php.ini 中设置了 allow_url_fopen,这将起作用。如果不是,则必须使用 CURL 获取图像,然后使用 file_put_contents() 写入。
    【解决方案2】:

    还有一种简单的方法:

    $img = 'http://www.domain.com/image.jpg';
    $img = imagecreatefromjpeg($img);
    $path = '/local/absolute/path/images/';
    imagejpeg($img, $path);
    

    上面关于allow_url_fopen 的评论也适用于这个方法。如果您有一个相当严格的主机,您可能需要使用 cURL 来解决这个问题:

    /**
     * For when allow_url_fopen is closed.
     * 
     * @param  string  $img       The web url to the image you wish to dl
     * @param  string  $fullpath  The local absolute path where you want to save the img
     */
    function save_image($img, $fullpath) {
        $ch = curl_init ($img);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $binary_img = curl_exec($ch);
        curl_close ($ch);
        if (file_exists($fullpath)){
            unlink($fullpath);
        }
    
        $fp = fopen($fullpath, 'x');
        fwrite($fp, $binary_img);
        fclose($fp);
    }
    

    【讨论】:

    • 您提出的第一种方法将比简单地复制图像涉及更多的开销。
    • 唉,它允许你用一些 GD 技巧来操纵图像。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2017-02-07
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多