Reputation: 15798
I want to convert image from its url to base64.
Upvotes: 32
Views: 94622
Reputation: 515
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.
Upvotes: 31
Reputation: 2100
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);
Upvotes: 13
Reputation: 30996
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.
Upvotes: 62
Reputation: 4147
I'm not sure, but check this example http://www.php.net/manual/es/function.base64-encode.php#99842
Regards!
Upvotes: 1