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…

Dicembre 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

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.