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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM