Last active
December 18, 2015 13:29
-
-
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.
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 | |
/** | |
* 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