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

时间:2014-05-16 18:36:52

标签: php html 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);

2 个答案:

答案 0 :(得分: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.'"/>';

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

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

答案 1 :(得分:2)

你可以试试这个

<img src="/path/to/yourimage.php">

在yourimage.php。

$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);