PHP 之 图像の疑问

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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值