Saving image from PHP URL

后端 未结 12 1750
日久生厌
日久生厌 2020-11-21 17:10

I need to save an image from a PHP URL to my PC. Let\'s say I have a page, http://example.com/image.php, holding a single \"flower\" image, nothing else. How ca

相关标签:
12条回答
  • 2020-11-21 18:14

    Here you go, the example saves the remote image to image.jpg.

    function save_image($inPath,$outPath)
    { //Download images from remote server
        $in=    fopen($inPath, "rb");
        $out=   fopen($outPath, "wb");
        while ($chunk = fread($in,8192))
        {
            fwrite($out, $chunk, 8192);
        }
        fclose($in);
        fclose($out);
    }
    
    save_image('http://www.someimagesite.com/img.jpg','image.jpg');
    
    0 讨论(0)
  • 2020-11-21 18:15

    install wkhtmltoimage on your server then use my package packagist.org/packages/tohidhabiby/htmltoimage for generate an image from url of your target.

    0 讨论(0)
  • 2020-11-21 18:16

    Vartec's answer with cURL didn't work for me. It did, with a slight improvement due to my specific problem.

    e.g.,

    When there is a redirect on the server (like when you are trying to save the facebook profile image) you will need following option set:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    

    The full solution becomes:

    $ch = curl_init('http://example.com/image.php');
    $fp = fopen('/my/folder/flower.gif', 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    
    0 讨论(0)
  • 2020-11-21 18:17
    copy('http://example.com/image.php', 'local/folder/flower.jpg');
    
    0 讨论(0)
  • 2020-11-21 18:17

    I wasn't able to get any of the other solutions to work, but I was able to use wget:

    $tempDir = '/download/file/here';
    $finalDir = '/keep/file/here';
    $imageUrl = 'http://www.example.com/image.jpg';
    
    exec("cd $tempDir && wget --quiet $imageUrl");
    
    if (!file_exists("$tempDir/image.jpg")) {
        throw new Exception('Failed while trying to download image');
    }
    
    if (rename("$tempDir/image.jpg", "$finalDir/new-image-name.jpg") === false) {
        throw new Exception('Failed while trying to move image file from temp dir to final dir');
    }
    
    0 讨论(0)
  • 2020-11-21 18:17
    $img_file='http://www.somedomain.com/someimage.jpg'
    
    $img_file=file_get_contents($img_file);
    
    $file_loc=$_SERVER['DOCUMENT_ROOT'].'/some_dir/test.jpg';
    
    $file_handler=fopen($file_loc,'w');
    
    if(fwrite($file_handler,$img_file)==false){
        echo 'error';
    }
    
    fclose($file_handler);
    
    0 讨论(0)
提交回复
热议问题