数据图像 URI 无效

Data Image URI not working

我正在尝试通过用 DATA-URI 替换图像 URL 来优化我的页面,但图像在转换为 DATA URI 后无法呈现。

这是我将普通 url 转换为数据 uri 的代码:

$imgurl= "https://www.cashy.in/images/banners/0ad08aafdd0887ed79f9fcc4321d54ed.png";
$type=substr($imgurl, -3);
$newimg=base64_encode($imgurl);
$o_img="data:image/".$type.";base64,".$newimg;

如上所述,您不对图像本身的 URL 进行编码,您必须对实际数据进行编码。

因此,您应该使用如下代码:

$imgurl= "https://www.cashy.in/images/banners/0ad08aafdd0887ed79f9fcc4321d54ed.png";
$type=substr($imgurl, -3);
$newimg=base64_encode(file_get_contents($imgurl));
$o_img="data:image/".$type.";base64,".$newimg;

但是,在执行此操作时,您需要了解生成的 HTML 的大小增加了图像的大小(加上 base64 编码固有的 33% 开销)。仅当图像本身非常小并且额外 HTTP 请求的开销超过所需的额外下载时才执行此操作。