How to convert an image to base64 encoding?

前端 未结 9 1224
刺人心
刺人心 2020-11-22 06:01

Can you please guide me how can I convert an image from a URL to base64 encoding?

相关标签:
9条回答
  • 2020-11-22 06:42

    Here is an example using a cURL call.. This is better than the file_get_contents() function. Of course, use base64_encode()

    $url = "http://example.com";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    ?>
    
    <img src="data:image/png;base64,<?php echo base64_encode($output);?>">  
    
    0 讨论(0)
  • 2020-11-22 06:44
    <img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">
    

    I was trying to use this resource but kept getting an error, I found the code above worked perfectly.

    Just replaced IMAGE URL HERE with the URL of your image - http://www.website.com/image.jpg

    0 讨论(0)
  • 2020-11-22 06:52

    You can also do this via curl, just you need a path to an image file and pass it to the function given below..

    public static function getImageDataFromUrl($url)
    {
        $urlParts = pathinfo($url);
        $extension = $urlParts['extension'];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($response);
        return $base64;
    
    }
    
    0 讨论(0)
提交回复
热议问题