覺得用php寫程式來處理圖片和做一個驗證碼比較有意思,所以就寫了一個簡單公用函數庫,跟大家分享
<?php
/*公用函數*/
/*載入圖片*/
function load_picture($path)
{
$info = getimagesize($path);
switch($info[2])
{
case 1:
$im = imagecreatefromgif($path);
return $im;
case 2:
$im = imagecreatefromjpeg($path);
return $im;
case 3:
$im = imagecreatefrompng($path);
return $im;
}
}
/*改變圖片的大小*/
function change_picture_size($path,$size)
{
$im = load_picture($path);
$info = getimagesize($path);
$width = $info[0]*$size;
$height = $info[1]*$size;
$new = imagecreatetruecolor($width,$height);
$res = imagecopyresized($new,$im,0,0,0,0,$width,$height,$info[0],$info[1]);
if($res)
{
return $new;
}
else
echo "<br>Sorry ,failed!<br>";
}
/*增加字型浮水印*/
function add_fonts($im,$fontsize,$liner,$x,$y,$content)
{
$te = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
imagettftext($im,$fontsize,$liner,$x,$y,$te,"FZFangSong.ttf",$content);
}
/*增加圖片浮水印*/
function add_water_code($dim,$sim_path,$x,$y,$cut_x,$cut_y,$width,$height)
{
$sim = load_picture($sim_path);
imagecopy($dim,$sim,$x,$y,$cut_x,$cut_y,$width,$height);
}
/*產生驗證碼*/
function check_code()
{
//產生隨機數
for($i=0;$i<4;$i++)
{
$rand .=dechex(rand(0,15));
}
//建立圖片
$im = imagecreatetruecolor(100,30);
//建立調色盤
$bg = imagecolorallocate($im,0,0,0);
$te = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
//寫隨機數
//imagestring($im,4,rand(20,60),rand(8,16),$rand,$te);
//寫漢字
//$content = iconv("gbk","UTF-8","生日快樂");(windows下需要使用)
imagettftext($im,15,0,rand(20,50),rand(16,20),$te,"FZFangSong.ttf","生日快樂");
//畫點和畫畫線
for($j=0;$j<5;$j++)
{
imageline($im,100,30,rand(0,100),rand(0,30),$te);
}
for($j=0;$j<100;$j++)
{
imagesetpixel($im,rand(0,100),rand(0,30),$te);
}
return $im;
}
//測試
$path = "picture/1.jpg";
$pic = change_picture_size($path,"0.5");
add_fonts($pic,48,0,50,50,"中國你好");
add_water_code($pic,"picture/2.jpg",50,200,10,20,100,100);
//$imge = check_code();
header("Content-type:image/jpeg");
imagejpeg($pic);
?>