Mar*_*lor 10 html php gd image
在PHP manualfor中base64_encode()我看到了以下用于输出图像的脚本.
<?php
$imgfile = "test.gif";
$handle = fopen($filename, "r");
$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';
?>
Run Code Online (Sandbox Code Playgroud)
但是如何输出动态创建的图像GD?
我试过这个:
$im = imagecreatetruecolor(400, 400);
imagefilledrectangle($im, 0, 0, 200, 200, 0xFF0000);
imagefilledrectangle($im, 200, 0, 400, 200, 0x0000FF);
imagefilledrectangle($im, 0, 200, 200, 400, 0xFFFF00);
imagefilledrectangle($im, 200, 200, 400, 400, 0x00FF00);
echo '<img src="data:image/png;base64,'.base64_encode(imagepng($im)).'" />';
Run Code Online (Sandbox Code Playgroud)
为什么不起作用?
它似乎适用于IE但不适用于Firefox.如何让它跨浏览器?
Tom*_*zyk 15
好的,抱歉,我的想法太快了:)
imagepng()将原始数据流直接输出到浏览器,因此您必须使用ob_start()和其他输出缓冲句柄来获取它.
这个给你:
ob_start();
imagepng($yourGdImageHandle);
$output = ob_get_contents();
ob_end_clean();
Run Code Online (Sandbox Code Playgroud)
那就是 - 你需要$output为你的base64_encode()函数使用变量.
And*_*rew 11
因为imagepng直接输出bool或图像流到输出.
因此,为了获取图像数据,您应该使用如下输出缓冲区:
ob_start();
imagepng($im);
$image = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/png;base64,'.base64_encode($image).'" />';
Run Code Online (Sandbox Code Playgroud)