从DataURL创建/显示图像

6

能否通过接收到的POST数据URL创建和显示图片文件?就像这样:

<?
$imgstr = $_POST["imgdata"]; //data:image/png;base64,.... etc (it's always PNG)
echo base64_decode($imgstr); // idk what this really does
?>

我无法使用<img>标签来显示它。它需要像一个“正常”的图像文件一样工作。

3个回答

6

是的,请尝试:

<img alt="Base64 Image" src="data:image/png;base64,{$imgstr}" />

编辑:请确保您清理了$_POST,这样人们就不会插入危险的垃圾...


4

如果您的输入是

// Red dot graphic, stolen from Wikipedia
$imgstr = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

那么,您可以随意使用这个东西。
// Grab the MIME type and the data with a regex for convenience
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
    die("error");
}

// Decode the data
$content = base64_decode($matches[2]);

// Output the correct HTTP headers (may add more if you require them)
header('Content-Type: '.$matches[1]);
header('Content-Length: '.strlen($content));

// Output the actual image data
echo $content;
die;

1

在输出之前,您必须设置正确的标题。

header( 'Content-Type: image/jpeg' );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接