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.

Recommended

Find values recursively inside complex json objects in PHP

A PHP function to to quickly search complex, nested php structures for specific values.

Dicembre 18, 2022

Test page for Bright Links plugin

To test the plugin hover your mouse to a link, or tap the link on mobile device.

Dicembre 4, 2022

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

Febbraio 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

Novembre 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…

Settembre 2, 2016

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

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

Settembre 22, 2015