Ven*_*Rao 2 php png image laravel
我使用HTML2Canvas为我的页面上的div创建了一个png图像,它为图像创建了base64编码的字符串.我将其作为内联显示在页面上:
<img id="headerImage" src="data:image/png;base64,iVBORw0KGg..." width="60">Run Code Online (Sandbox Code Playgroud)
然后我将它作为LONGTEXT保存在我的数据库中.
在我的控制器中,我似乎无法将图像作为有效的PNG服务器.尝试了一系列不同的方法,如代码片段所示:
$imageStr = $plan->image;
$pos = strpos($imageStr, ',');
$trimmed = substr($imageStr, $pos+1);
$image = base64_decode($trimmed);
/*
$im = imagecreatefromstring($image);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
} else {
echo 'Failed';
}
return;
*/
$response = Response::make(trim($image), 200);
$response->header('Content-Type', 'image/png');
return $response;
/*
return Response::stream(function() use ($image) {
echo $image;
}, 200, array('Content-Type:image/png'));
*/Run Code Online (Sandbox Code Playgroud)
当我查看标题时,它看起来很合理:
t=4102 [st=437] HTTP_TRANSACTION_READ_RESPONSE_HEADERS
--> HTTP/1.1 200 OK
Date: Tue, 24 Feb 2015 16:36:28 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.5
Cache-Control: no-cache
Set-Cookie: [362 bytes were stripped]
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: image/png
t=4102 [st=437] -HTTP_TRANSACTION_READ_HEADERSRun Code Online (Sandbox Code Playgroud)
在所有情况下,浏览器都会显示损坏的图像符号.在这一点上我的智慧结束 - 欣赏有关如何做到这一点的任何想法!
您的代码应该按原样运行.
关于Base64编码图像的说明; 要再次解码它们,您必须删除data:image/png;base64字符串的一部分.
所以:
<?php
$imageStr = $plan->image; // Or wherever you get your string from
$image = base64_decode(str_replace('data:image/png;base64,', '', $imageStr));
$response = Response::make($image, 200);
$response->header('Content-Type', 'image/png');
return $response;
Run Code Online (Sandbox Code Playgroud)
此外,imagecreatefromstring在这种情况下也是多余的.