處理圖像
處理圖像一般步驟:
1、設定標頭
2、創建畫布
3、填充背景
4、繪製輪廓
5、輸出最終圖形
6、清楚資源
7、其他文件調用圖像
// 第一步:設置文件MIME輸出類型
// 將輸出類型改成圖像流
header('Content-Type:image/png;');
//第二步:創建一個圖像區域,圖像背景
//有兩種創建方式 資源類型 一般加上@符號,防止出錯
//這個函數創建了一個圖像區域,沒有進行填充的時候,背景默認黑色
$im = imagecreatetruecolor(200, 200);
//第三步:在空白圖像區域 繪製顏色 文字線條等
//填充色換掉 首先要有個顏色填充器
//imagecolorallocate();爲顏色填充器
$blue = imagecolorallocate($im, 0, 102, 255);
//將這個blue顏色填充到背景上去
imagefill($im, 0, 0, $blue);
//第四步:在藍色背景上輸入一些線條
$white = imagecolorallocate($im, 255, 255, 255);
//imageline畫一條線段
imageline($im, 0, 0, 200, 200, $white);
imageline($im, 200, 0, 0, 200, $white);
//繪製文本 imagestring
imagestring($im, 5, 80, 20, 'Mr Lee', $white);
//第五步:輸出最終圖形
//以PNG格式將圖像輸出到瀏覽器
imagepng($im);
1、簡單驗證碼實現
//創建一個四位數驗證碼
$a=''; //可以不定義,但我的機器會報錯
for($i=0;$i<4;$i++){
$a = dechex(mt_rand(0,15)).$a;
}
header('Content-Type:image/png');
$im = imagecreatetruecolor(75, 25);
$blue = imagecolorallocate($im, 0, 102,255);
$white = imagecolorallocate($im,255,255,255);
imagefill($im,0,0,$blue);
imagestring($im,5,20,5,$a,$white);
imagepng($im);
imagedestroy($im);
2、給圖片添加水印
//加載已有的圖像
header('Content-Type:image/png');
//imagecreatefrompng--從PNG文件或URL創建一個新圖像
//用image載入圖像,是可以編輯圖像
//在載入圖像中 加入一個水印
$im = @imagecreatefrompng('222.png');//當前目錄下的"222.png";
//$im = @imagecreatefromjpeg($filename);
$white = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 3, 0,0,"Hello World", $white);
imagepng($im);
//imagejpeg($image);
imagedestroy($im);