Embedding images in HTML or CSS with PHP

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of…

December 4, 2013

This small function returns an encoded string to embed images, inline, inside your html/css code and reduce the number of calls to the server and speed up page load.

function encodeimg($file) {
	$contents = file_get_contents($file);
	$base64 = base64_encode($contents);
	$imagetype = exif_imagetype($file);
	$mime = image_type_to_mime_type($imagetype);
	return "data:$mime;base64,$base64";
}

Example of usage to inline an image:

echo "<img src='".encodeimg("minibots/avatar.jpg")."'/>";

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

November 7, 2019

Highlight text for search results in PHP

Useful code to highlight text occurences in search results or in a text. How to highlight text in a string…

September 2, 2016

How to add rel=”nofollow” to links with preg_replace()

Adding rel="nofollow" to external link is a good SEO practice.

September 22, 2015

Limit the number of categories for posts in WordPress

CHOOSE ONLY ONE CATEGORY WORDPRESS If you need to limit the number of categories used by the authors of your…

September 14, 2015

Reordering rows records on a mysql table with PHP

This PHP function lets you reorder records on a table when you have a field used for save the position.…

December 18, 2013