网页的信息图形可视化:有没有更好的方法来代替小的 PNG 文件?

Information graphical visualization for web-page: Is there any better way instead of small PNG files?

先描述一下任务:

我想创建一个网页,其中包含多行文本和每行一个小(假设为 100 x 20 像素)图形。每个图形都是动态生成的(因此每次加载页面时都会是一个新图形)。

我自己能想到的唯一方法是在每次指示行时在服务器上创建一个新的 PNG 文件,并将 link 添加到这个新创建的文件到 HTML:<img src='row1graph.png'>.

如果页面是单个图像 - 我可以将它直接输出到浏览器,但我的情况不是这样。

那么问题来了:有没有更好的方法来处理这样的图片,跳过不必要的磁盘访问操作?

有两种方法可以优化网页中的小图形。您可以使用 tile-set 概念(单个图像中的所有图形,具有基于例如背景位置的偏移),或者您可以将 PNG 作为 base-64 直接嵌入到页面中:

<img alt="Embedded Image" src="data:image/png;base64,yourbase64image" />

根据文件大小和浏览器支持,这些选项有不同的优点。当然,两者可以组合 - 您可以拥有一个嵌入式拼贴集。

好吧,如果您想避免 "unnecessary disk access",并且由于图像尺寸较小,您可以使用 Base64 encoding。您也可以将编码后的字符串存储在数据库中。

这样 <img src='row1graph.png'> 就变成了...

<img src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD//gA8Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2ODApLCBxdWFsaXR5ID0gMTAwCv/bAEMAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/bAEMBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIABQAZAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ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sdIM33XYPNYaZDOPMJw5WVWI4DDrWRof7QHxi/Z/+K2oWXwl8f8AiTwm4RYzfQ6re39463ERScyf2pPe2srSozK5ktW+ViBjNFFXhsNhsPClPD4ehQnTqR5JUaVOlKFo3XJKEYuNnqrNWep5+MxeKxcqsMVicRiYVYzjVhiK1StGrGSSlGpGpKSnGS0kpJprRo/pM/ZQ/bX+PfjT4M6HrXi3XdF8Qaybu7tJdUvvD9hHd3EVtHbCMz/YRaQPJlnZ5BCrOzEk4wAUUV9/QnOVGk5Sk24Rbbk222tW23dt92fkmKweEjia8Y4XDRjGrNJRoUkklJ2SSjZJWVktrLsf/9k="/>

您可以从 PHP 而不是从文件提供图像 - 我的意思是您可以 PHP 动态创建图像并提供它,而不必在网络服务器的文件系统中有一个文件并且必须在 HTML.

标签的 src 字段中按名称引用它

所以,而不是

<image src="xyz.png" alt="..." size="...">

你可以使用

<img src="/php/thumb.php?param1=128&param2=45"/>

这会导致在呈现页面时调用 /php/thumb.php 处的 PHP 脚本。在该脚本中,您可以像这样动态创建图像(如果您愿意,可以使用额外的参数):

<?php    
header("Content-type: image/png");
$p1 = $_GET['param1'];
$p2 = $_GET['param2'];

// Create a 200x200 image
$im    = imagecreatetruecolor(200,200);
$white = imagecolorallocate($im, 255, 255, 255);
$red   = imagecolorallocate($im, 255, 0, 0);

// Here you can draw in the image, write on it, set any pixels, calculate any colours you wish

// Draw a white rectangle, then a red one
imagefilledrectangle($im, 50, 50, 100, 100, $white);
imagefilledrectangle($im, 75, 75, 150, 150, $red);

imagepng($im);
imagedestroy($im);
?>

我在前 3 行之后省略了一些代码,因此您只看到了技巧,而不是我代码的所有血淋淋的细节。您感兴趣的实际线路是:

header(...image/png);

它告诉浏览器即将到来的内容类型 - 即图像,并且

imagepng();

它实际上将 PNG 数据流发送到浏览器。

上面的代码在浏览器中产生了这个: