1、为什么生成图像,浏览器仅会显示有小方格的黑色页面(下图所示),而不是我预期的图像效果呢?
其中多数人应该是将图像生成嵌入到html代码里面去(下图所示)
<html>
<head>
</head>
<body>
<?php
header("content-type:image/png");
$img = imagecreate(150, 40);
imagecolorallocate($img, 245, 245, 245);
imagepng($img);
imagedestroy($img);
?>
</body>
</html>
如果是这样操作,会受到浏览器背景色和图层的问题,目前我经过尝试有两种方法:
(1)调用ob_clean()函数即可呈现出你预期的图片效果,但其周围还是会有黑色背景色(这个怎么处理,正在研究中)
(2)将这段php代码放在新的php文件,再用img标签去调用即可完美达到预期效果(推荐用这种,非常方便理解)
2、当用imagecreat去创建图像,且使用了较多的imageline后,会发现部分元素丢失现象
问题代码呈现:
<?php
header("Content-type:image/PNG");
$width = 150;
$height = 40;
$img = imagecreate($width, $height);
$back = imagecolorallocate($img,255,165,0);
imagefill($img, 0, 0, $back);
for($i = 0; $i <= 200; $i++){
$randcolor = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $randcolor);
$randcolor2 = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($img, rand(0, $width), rand(0, $height), $randcolor2);
}
$text_color = imagecolorallocate($img, rand(100, 255), rand(0, 100), rand(100, 255));
imagestring($img, 5, 50, 13, "hello world", $text_color);
imagepng($img);
imagedestroy($img);
?>
效果为:
这个问题是imageline所创建的线条过多,导致图像显示不正常,包括后面的字体无法显示
也是两种处理方式:
(1)在imagecreate下,创建的线条数尽量不要太多
(2)改用imagecreatetruecolor,不会有此问题,但如果将字体的图层实现放在创建线条前面,线条过多也一样无法显示请出(如下面代码片段)
$text_color = imagecolorallocate($img, rand(100, 255), rand(0, 100), rand(100, 255));
imagestring($img, 5, 50, 13, $str, $text_color);
for($i = 0; $i <= 200; $i++){
$randcolor = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($img, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $randcolor);
$randcolor2 = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($img, rand(0, $width), rand(0, $height), $randcolor2);
}