如果您像我一样浏览页面标记,您肯定会在图像 src 属性中看到数据 URI 的使用。图像文件数据不是为图像提供传统地址,而是采用 base64 编码并填充在 src 属性中。这样做可以节省每个图像的网络请求,如果您是偏执狂类型,可以防止目录路径暴露。由于创建数据 URI 非常容易,让我向您展示如何使用 PHP 来完成。
PHP
首先使用 file_get_contents
(或您喜欢的任何其他 PHP 方法)读取图像,然后使用 base64_encode
将图像转换为 base64:
// A few settings $image = 'cricci.jpg'; // Read image path, convert 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 a sample image echo '';
对于 base64 格式的图像数据,最后一步是将该数据放入数据 URI 格式中,包括图像的 MIME 类型。这将是一个很好的功能:
function getDataURI($image, $mime = '') { return 'data: '.(function_exists('mime_content_type') ? mime_content_type($image) : $mime).';base64,'.base64_encode(file_get_contents($image)); }
要记住的是 IE7 和更低版本不支持数据 URI,所以如果您正在考虑从图像路径切换到数据 URI,请记住这一点!