Can you please guide me how can I convert an image from a URL to base64 encoding?
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);?>">
<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
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;
}