php gd库 图像操作

PHP GD库

  • 使用GD需要开启 PHP默认会开启
  • 如果没有开启 则需要在php.ini 把extension=php_gd2.dll前面的分号去掉 重启apache

  • 画出一个红色的正方形

  •  <?php
     	//发送一个原生的HTTP头 
     	header("content-type:image/png");
     	//新建一个真彩色画布
     	$img = imagecreatetruecolor(100,100);
     	//为图像分配颜色
     	$red = imagecolorallocate($img,0xFF,0x00,0x00);
     	//区域填充
     	imagefill($img);
     	//以 PNG 格式将图像输出到浏览器或文件
     	imagepng($img);
     	//销毁一图像 释放内存
     	imagedestroy($img);
     ?>
    
  • 画线条

  • 函数bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )

  • imageline() 用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2(图像左上角为 0, 0)画一条线段。

    <?php
    	//创建画布
    	$img = imagecreatetruecolor(100,100);
    	//为图像分配颜色
    	$red = imagecolorallocate($img,0xFF,0x00,0x00);
    	//画线条
    	imageline($img,0,0,100,100,$red);
    	//输出头信息
    	header('content-type:image/png');
    	//声明格式 imagepng ( resource $image [, string $filename ] )如果给了参数 $filename 则将图像保存至 $filename 中
    	imagepng($img);
    	//销毁图像 释放内存		
    	imagedestroy($img);
    
    
    ?>
    
  • 绘制文字

  • imagestring() 用 col 颜色将字符串 s 画到 image 所代表的图像的 x,y 坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果 font 是 1,2,3,4 或 5,则使用内置字体。

     bool imagestring ( resource $image , int $font , int $x , int $y , string $s , int $col )
    
  • 小例子 验证码:

  • 采用imagesetpixel函数来实现干扰

	    <?php
		$img = imagecreatetruecolor(100, 40);
		$black = imagecolorallocate($img, 0x00, 0x00, 0x00);
		$green = imagecolorallocate($img, 0x00, 0xFF, 0x00);
		$white = imagecolorallocate($img, 0xFF, 0xFF, 0xFF);
		imagefill($img,0,0,$white);
		//生成随机的验证码
		$code = '';
		for($i = 0; $i < 4; $i++) {
		    $code .= rand(0, 9);
		}
		imagestring($img, 5, 10, 10, $code, $black);
		//加入噪点干扰
		for($i=0;$i<50;$i++) {
		  imagesetpixel($img, rand(0, 100) , rand(0, 100) , $black); 
		  imagesetpixel($img, rand(0, 100) , rand(0, 100) , $green);
		}
		//输出验证码
		header("content-type: image/png");
		imagepng($img);
		imagedestroy($img);
                    ?>
  • 添加水印

      <?php
      //这里仅仅是为了案例需要准备一些素材图片
      $url = 'http://www.iyi8.com/uploadfile/2014/0521/20140521105216901.jpg';
      $content = file_get_contents($url);
      $filename = 'tmp.jpg';
      file_put_contents($filename, $content);
      $url = 'http://wiki.ubuntu.org.cn/images/3/3b/Qref_Edubuntu_Logo.png';
      file_put_contents('logo.png', file_get_contents($url));
      //开始添加水印操作
      $im = imagecreatefromjpeg($filename);
      $logo = imagecreatefrompng('logo.png');
      $size = getimagesize('logo.png');
      imagecopy($im, $logo, 15, 15, 0, 0, $size[0], $size[1]); 
       
      header("content-type: image/jpeg");
      imagejpeg($im);
    
  • 以上代码参考 http://www.imooc.com/learn/26

posted @ 2017-05-22 22:04  青柚  阅读(2657)  评论(0编辑  收藏  举报