PHP: How to convert an image from URL to Base64?
I want t开发者_如何学运维o convert image from its url to base64.
Do you want to create a data url? You need a MIME-Type and some other additional information then (see Wikipedia). If this is not the case, this would be a simple base64 representation of the image:
$b64image = base64_encode(file_get_contents('path/to/image.png'));
Relevant docs: base64_encode()
-function, file_get_contents()
-function.
I got to this question searching for a similar solution, actually, I understood that this was the original question.
I wanted to do the same, but the file was in a remote server, so this is what I did:
$url = 'http://yoursite.com/image.jpg';
$image = file_get_contents($url);
if ($image !== false){
return 'data:image/jpg;base64,'.base64_encode($image);
}
So, this code is from a function that returns a string, and you can output the return value inside the src parameter of an img tag in html. I'm using smarty as my templating library. It could go like this:
<img src="<string_returned_by_function>">
Note the explicit call to:
if ($image !== false)
This is necessary because file_get_contents can return 0 and be casted to false in some cases, even if the file fetch was successful. Actually in this case it shouldn't happen, but its a good practice when fetching file content.
Try this:-
Example One:-
<?php
function base64_encode_image ($filename=string,$filetype=string) {
if ($filename) {
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
}
?>
used as so
<style type="text/css">
.logo {
background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>
or
<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
Example Two:-
$path= 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
I'm not sure, but check this example http://www.php.net/manual/es/function.base64-encode.php#99842
Regards!
base64_encode
精彩评论