php文件名是image.func.php
<?php
session_start();
// //創建畫布
$width=80;
$height=28;
$image=imagecreatetruecolor($width, $height);//返回以畫像,默認黑色
$white=imagecolorallocate($image,255,255,255);//爲畫布上色
$black=imagecolorallocate($image,0,0,0);//爲畫布上色
// //用填充矩形填充畫布
//imagefilledrectangle()意思是在$image畫布上畫了一個$white顏色的矩形,其左上角座標爲 x1,y1,右下角座標爲 x2,y2。0, 0 是圖像的最左上角。並無返回數據
imagefilledrectangle($image, 0, 0, $width, $height, $white);
$chars=buildRandomString($type,$length);
$_SESSION[$sess_name]=$chars;
$fontfiles=array("msyh.ttc","msyhbd.ttc","msyhl.ttc","simsun.ttc");
for ($i=0; $i <$length ; $i++) {
//mt_rand()生成x到y範圍內隨機數
$size=mt_rand(14,18);
$angle=mt_rand(-15,15);
$x=5+$i*$size;
$y=mt_rand(20,26);
$color=imagecolorallocate($image,mt_rand(50,90),mt_rand(80,200),mt_rand(90,180));
$fontfile="../fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)];
$text=substr($chars,$i,1);
//向圖像寫入文本
imagettftext($image,$size,$angle,$x,$y,$color,$fontfile,$text);
}
if ($pixel) {
for ($i=0; $i < 50; $i++) {
//imagesetpixel() 在 image 圖像中用 color 顏色在 x,y 座標(圖像左上角爲 0,0)上畫一個點。
imagesetpixel($image,mt_rand(0,$width-1),mt_rand(0,$height-1),$black);
}
}
if ($line) {
for ($i=1; $i < $line; $i++) {
$color=imagecolorallocate($image,mt_rand(50,90),mt_rand(80,200),mt_rand(90,180));
//imageline() 用 color 顏色在圖像 image 中從座標 x1,y1 到 x2,y2(圖像左上角爲 0, 0)畫一條線段。
imageline($image,mt_rand(0,$width-1),mt_rand(0,$height-1),mt_rand(0,$width-1),mt_rand(0,$height-1),$color);
}
}
header("content-type:image/png");
//imagegif — 輸出圖象到瀏覽器或文件。
// imagegif($image);
imagepng($image);
imagedestroy($image);
?>
html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img src="http://localhost/PHPDemo/lib/image.func.php" οnclick="getVerify()" id="verify">
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getVerify() {
$("#verify").attr("src","http://localhost/PHPDemo/lib/image.func.php");
}
</script>
</body>
</html>