图像uri错误啥意思_使用PHP的图像数据URI

本文介绍了如何使用PHP将图像转换为base64编码的数据URI,以减少网络请求并保护目录路径。通过读取图像,然后使用base64_encode()函数,可以创建数据URI。需要注意的是,IE7及更低版本浏览器不支持这种技术。
摘要由CSDN通过智能技术生成

图像uri错误啥意思

If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves a network request for each image, and if you're the paranoid type, can prevent exposure of directory paths. Since creating data URIs is incredibly easy, let me show you how to do it with PHP.

如果您像我一样拖曳页面标记,则毫无疑问,您会看到image src属性中使用了数据URI。 图像文件数据不是对图像提供传统地址,而是对base64编码并填充在src属性中。 这样做可以保存每个图像的网络请求,并且如果您是偏执狂类型的话,可以防止暴露目录路径。 由于创建数据URI非常简单,所以让我向您展示如何使用PHP。

PHP (The PHP)

Start by reading in the image using file_get_contents (or any other PHP method you'd like), then convert the image to base64 using base64_encode:

首先使用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 '
   
   
';

With the image data in base64 format, the last step is placing that data within the data URI format, including the image's MIME type. This would make for a good function:

对于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));
}


The thing to remember is that IE7 and lower don't support data URIs, so keep that in mind if you're considering switching from image paths to data URIs!

要记住的是,IE7和更低版本不支持数据URI,因此,如果您正在考虑从图像路径切换到数据URI,请记住这一点!

翻译自: https://davidwalsh.name/data-uri-php

图像uri错误啥意思

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值