使用PHP在html文档中显示带有原始图像数据的PNG

Rob*_*ert 2 html php png libpng

使用此代码,我尝试从JSON创建签名图像,然后直接在浏览器中显示图像而不保存它.我遇到的问题是我想在HTML文档中显示此图像,因此标题信息已被修改.有没有办法在HTML文档中显示原始图像数据中的图像?或者围绕这个问题的任何其他方式?

$json = $ticket->sig; // get the json representing the signature
$img = sigJsonToImage($json);  //get image resource from json

    // HERE I WANT TO DISPLAY THE IMAGE BUT GET Cannot modify header information
header('Content-Type: image/png');
imagepng($img, null, 0, PNG_NO_FILTER);
imagedestroy($img);
Run Code Online (Sandbox Code Playgroud)

Luc*_*ske 10

当然,你可以一起使用两件事.

HTML Image标记支持base64编码图像.对于html来说它可能很大,但会起作用.您还可以使用ob_start和ob_end函数将图像输出到缓冲区.见http://us2.php.net/manual/pt_BR/function.ob-start.php

所以对于PHP文件,你可以这样做:

$json = $ticket->sig; // get the json representing the signature
$img = sigJsonToImage($json);  //get image resource from json

ob_start(); // Start buffering the output
imagepng($img, null, 0, PNG_NO_FILTER);
$b64 = base64_encode(ob_get_contents()); // Get what we've just outputted and base64 it
imagedestroy($img);
ob_end_clean();

// Print the HTML tag with the image embedded
echo '<img src="data:image/png;base64,'.$b64.'"/>';
Run Code Online (Sandbox Code Playgroud)

这将生成带有嵌入图像的HTML Img标记.希望这就是你想要的.

PS:请记住,这会增加HTML数据的加载时间,因为如果您只是链接它,浏览器会打开另一个下载图像的线程.