Image to Data URI with PHP

posted by Matt Adams

I often find myself converting images to data URIs in an attempt to reduce network requests. This script is based on the same concept as David Walsh’s article Image Data URIs with PHP but rather than using the depreciated mime_content_type, my script makes use of FileInfo, which “provides the same functionality in a cleaner way” as quoted from the PHP docs.

echo '<img src="'.getDataURI('path_to/your_image.png').'">';
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));
}

Please keep in mind if you plan on using data URIs, they are not supported by ie7 and lower.