Skip to content

Instantly share code, notes, and snippets.

@mohamedsalehamin
Last active May 10, 2022 12:25
Show Gist options
  • Save mohamedsalehamin/acc2c9a55977beeac776c949d9d25271 to your computer and use it in GitHub Desktop.
Save mohamedsalehamin/acc2c9a55977beeac776c949d9d25271 to your computer and use it in GitHub Desktop.
Convert image to base64 using curl
<?php
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
function imageToBase64($image){
$imageData = base64_encode(curl_get_contents($image));
$mime_types = array(
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'odt' => 'application/vnd.oasis.opendocument.text ',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'gif' => 'image/gif',
'jpg' => 'image/jpg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'bmp' => 'image/bmp'
);
$ext = pathinfo($image, PATHINFO_EXTENSION);
if (array_key_exists($ext, $mime_types)) {
$a = $mime_types[$ext];
}
return 'data: '.$a.';base64,'.$imageData;
}
// How To Use it
echo '<img src="' . imageToBase64("https://mir-s3-cdn-cf.behance.net/project_modules/1400/1cb48c56801763.59bca8e44807a.jpg") . '" />';
@gitaeks
Copy link

gitaeks commented Aug 15, 2021

thank you.

@ezesoftchao
Copy link

Thanks

@RubenVianna
Copy link

thx o(°▽°)o

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment