32

I want to convert image from its url to base64.

0

4 Answers 4

62

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what if the url is external, like image from google, how do u handle it?
@AlbertoAcuña file_get_contents will download external urls as well
31

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.

Comments

13

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);

1 Comment

Your example two is exactly what I was looking for. +1 for this.
1

I'm not sure, but check this example http://www.php.net/manual/es/function.base64-encode.php#99842

Regards!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.