Skip to content

Instantly share code, notes, and snippets.

@amereservant
Last active December 18, 2015 13:29
Show Gist options
  • Save amereservant/5790788 to your computer and use it in GitHub Desktop.
Save amereservant/5790788 to your computer and use it in GitHub Desktop.
How to Base64 Encode images using PHP for both inline image elements and for CSS rules.
<?php
/**
* Base64 Encode images with PHP
*
* This example shows how to use PHP to Base64 encode images for both inline image
* elements as well as for CSS background image properties.
*
* @link https://gist.github.com/amereservant/5790788
*/
function base64_encode_image($filename='',$filetype='')
{
if($filename)
{
$imgbinary = fread(fopen($filename, 'r'), filesize($filename));
return 'data:image/'. $filetype .';base64,'. base64_encode($imgbinary);
}
} ?>
<html>
<head>
<style type="text/css">
.logo {
background: url("<?php echo base64_encode_image('img/logo.jpg','jpg'); ?>") no-repeat right 5px;
}
</style>
</head>
<body>
<img src="<?php echo base64_encode_image('img/logo.jpg','jpg'); ?>"/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment