Skip to content

Image Data URIs with PHP

Last updated on January 17, 2018

I often Use Image Data URIs for large-scale applications depending on client requirement(not supported in IE7 and below).

Data URI: The data URI scheme is a URI scheme that provides a way to include data in-line in web pages as if they were external resources. This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient.

Advantages of DATA URIs:
1.We can reduce the number of request to the network
2.we can Hide the file structure

NOTE: IE7 and Below versions didn’t support data URIs.

Here is the Code :

// Set image path
$image = 'cricci.jpg';

// Convert Image Path to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out image
echo '';

mime_content_type is depreciated, we can get the same output with FileInfo. let me show you

echo '';
function getDataURI($image,$mime='') {
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mime = $finfo->buffer(file_get_contents($image));
	return 'data:'.$mime.';base64,'.base64_encode(file_get_contents($image));
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments