Last active
May 10, 2022 12:25
-
-
Save mohamedsalehamin/acc2c9a55977beeac776c949d9d25271 to your computer and use it in GitHub Desktop.
Convert image to base64 using curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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") . '" />'; |
Thanks
thx o(°▽°)o
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you.