php 图片验证码

淡淡的烟草味﹌ 2022-06-10 03:41 557阅读 0赞

自己写的图片验证码demo

Center

先引用Image类 use Org\Util\Image;

  1. /**
  2. * 显示登录页面的验证码图片
  3. */
  4. public function verify() {
  5. ob_clean();
  6. Image::buildImageVerify(4, 1, 'png', 48, 22, C('CP_EXT_CFG.VERIFY_PRIFIX') . 'VRERIFY', false, false);
  7. }

页面调用(图片路径即为上面方法的路径)

  1. <input class="yzm" type="text" name="verify" placeholder="请输入验证码">
  2. <b><img id="verifyImg" src="verify'" style="width:100%;height:100%;"></b>
  3. //图片验证码
  4. $(document).ready(function () {
  5. $('#verifyImg').click(function () {
  6. var url = $(this).attr('src') + '&t=';
  7. $('#verifyImg').attr('src', url + (new Date()).valueOf().toString());
  8. });
  9. });
image类
  1. /**
  2. * 图像操作类库
  3. */
  4. class Image {
  5. /**
  6. * 取得图像信息
  7. * @static
  8. * @access public
  9. * @param string $image 图像文件名
  10. * @return mixed
  11. */
  12. static function getImageInfo($img) {
  13. $imageInfo = getimagesize($img);
  14. if ($imageInfo !== false) {
  15. $imageType = strtolower(substr(image_type_to_extension($imageInfo[2]), 1));
  16. $imageSize = filesize($img);
  17. $info = array(
  18. "width" => $imageInfo[0],
  19. "height" => $imageInfo[1],
  20. "type" => $imageType,
  21. "size" => $imageSize,
  22. "mime" => $imageInfo['mime']
  23. );
  24. return $info;
  25. } else {
  26. return false;
  27. }
  28. }
  29. /**
  30. * 为图片添加水印
  31. * @static public
  32. * @param string $source 原文件名
  33. * @param string $water 水印图片
  34. * @param string $$savename 添加水印后的图片名
  35. * @param string $alpha 水印的透明度
  36. * @return void
  37. */
  38. static public function water($source, $water, $savename = null, $alpha = 80) {
  39. //检查文件是否存在
  40. if (!file_exists($source) || !file_exists($water))
  41. return false;
  42. //图片信息
  43. $sInfo = self::getImageInfo($source);
  44. $wInfo = self::getImageInfo($water);
  45. //如果图片小于水印图片,不生成图片
  46. if ($sInfo["width"] < $wInfo["width"] || $sInfo['height'] < $wInfo['height'])
  47. return false;
  48. //建立图像
  49. $sCreateFun = "imagecreatefrom" . $sInfo['type'];
  50. $sImage = $sCreateFun($source);
  51. $wCreateFun = "imagecreatefrom" . $wInfo['type'];
  52. $wImage = $wCreateFun($water);
  53. //设定图像的混色模式
  54. imagealphablending($wImage, true);
  55. //图像位置,默认为右下角右对齐
  56. $posY = $sInfo["height"] - $wInfo["height"];
  57. $posX = $sInfo["width"] - $wInfo["width"];
  58. //生成混合图像
  59. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo['width'], $wInfo['height'], $alpha);
  60. //输出图像
  61. $ImageFun = 'Image' . $sInfo['type'];
  62. //如果没有给出保存文件名,默认为原图像名
  63. if (!$savename) {
  64. $savename = $source;
  65. @unlink($source);
  66. }
  67. //保存图像
  68. $ImageFun($sImage, $savename);
  69. imagedestroy($sImage);
  70. }
  71. function showImg($imgFile, $text = '', $x = '10', $y = '10', $alpha = '50') {
  72. //获取图像文件信息
  73. //增加图片水印输出,$text为图片的完整路径即可
  74. $info = Image::getImageInfo($imgFile);
  75. if ($info !== false) {
  76. $createFun = str_replace('/', 'createfrom', $info['mime']);
  77. $im = $createFun($imgFile);
  78. if ($im) {
  79. $ImageFun = str_replace('/', '', $info['mime']);
  80. //水印开始
  81. if (!empty($text)) {
  82. $tc = imagecolorallocate($im, 0, 0, 0);
  83. if (is_file($text) && file_exists($text)) {//判断$text是否是图片路径
  84. // 取得水印信息
  85. $textInfo = Image::getImageInfo($text);
  86. $createFun2 = str_replace('/', 'createfrom', $textInfo['mime']);
  87. $waterMark = $createFun2($text);
  88. //$waterMark=imagecolorallocatealpha($text,255,255,0,50);
  89. $imgW = $info["width"];
  90. $imgH = $info["width"] * $textInfo["height"] / $textInfo["width"];
  91. //$y = ($info["height"]-$textInfo["height"])/2;
  92. //设置水印的显示位置和透明度支持各种图片格式
  93. imagecopymerge($im, $waterMark, $x, $y, 0, 0, $textInfo['width'], $textInfo['height'], $alpha);
  94. } else {
  95. imagestring($im, 80, $x, $y, $text, $tc);
  96. }
  97. //ImageDestroy($tc);
  98. }
  99. //水印结束
  100. if ($info['type'] == 'png' || $info['type'] == 'gif') {
  101. imagealphablending($im, FALSE); //取消默认的混色模式
  102. imagesavealpha($im, TRUE); //设定保存完整的 alpha 通道信息
  103. }
  104. Header("Content-type: " . $info['mime']);
  105. $ImageFun($im);
  106. @ImageDestroy($im);
  107. return;
  108. }
  109. //保存图像
  110. $ImageFun($sImage, $savename);
  111. imagedestroy($sImage);
  112. //获取或者创建图像文件失败则生成空白PNG图片
  113. $im = imagecreatetruecolor(80, 30);
  114. $bgc = imagecolorallocate($im, 255, 255, 255);
  115. $tc = imagecolorallocate($im, 0, 0, 0);
  116. imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
  117. imagestring($im, 4, 5, 5, "no pic", $tc);
  118. Image::output($im);
  119. return;
  120. }
  121. }
  122. /**
  123. * 生成缩略图
  124. * @static
  125. * @access public
  126. * @param string $image 原图
  127. * @param string $type 图像格式
  128. * @param string $thumbname 缩略图文件名
  129. * @param string $maxWidth 宽度
  130. * @param string $maxHeight 高度
  131. * @param string $position 缩略图保存目录
  132. * @param boolean $interlace 启用隔行扫描
  133. * @return void
  134. */
  135. static function thumb($image, $thumbname, $type = '', $maxWidth = 200, $maxHeight = 50, $interlace = true) {
  136. // 获取原图信息
  137. $info = Image::getImageInfo($image);
  138. if ($info !== false) {
  139. $srcWidth = $info['width'];
  140. $srcHeight = $info['height'];
  141. $type = empty($type) ? $info['type'] : $type;
  142. $type = strtolower($type);
  143. $interlace = $interlace ? 1 : 0;
  144. unset($info);
  145. $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 计算缩放比例
  146. if ($scale >= 1) {
  147. // 超过原图大小不再缩略
  148. $width = $srcWidth;
  149. $height = $srcHeight;
  150. } else {
  151. // 缩略图尺寸
  152. $width = (int) ($srcWidth * $scale);
  153. $height = (int) ($srcHeight * $scale);
  154. }
  155. // 载入原图
  156. $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
  157. $srcImg = $createFun($image);
  158. //创建缩略图
  159. if ($type != 'gif' && function_exists('imagecreatetruecolor'))
  160. $thumbImg = imagecreatetruecolor($width, $height);
  161. else
  162. $thumbImg = imagecreate($width, $height);
  163. // 复制图片
  164. if (function_exists("ImageCopyResampled"))
  165. imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
  166. else
  167. imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
  168. if ('gif' == $type || 'png' == $type) {
  169. //imagealphablending($thumbImg, false);//取消默认的混色模式
  170. //imagesavealpha($thumbImg,true);//设定保存完整的 alpha 通道信息
  171. $background_color = imagecolorallocate($thumbImg, 0, 255, 0); // 指派一个绿色
  172. imagecolortransparent($thumbImg, $background_color); // 设置为透明色,若注释掉该行则输出绿色的图
  173. }
  174. // 对jpeg图形设置隔行扫描
  175. if ('jpg' == $type || 'jpeg' == $type)
  176. imageinterlace($thumbImg, $interlace);
  177. // 生成图片
  178. $imageFun = 'image' . ($type == 'jpg' ? 'jpeg' : $type);
  179. $imageFun($thumbImg, $thumbname);
  180. imagedestroy($thumbImg);
  181. imagedestroy($srcImg);
  182. return $thumbname;
  183. }
  184. return false;
  185. }
  186. /**
  187. * 根据给定的字符串生成图像
  188. * @static
  189. * @access public
  190. * @param string $string 字符串
  191. * @param string $size 图像大小 width,height 或者 array(width,height)
  192. * @param string $font 字体信息 fontface,fontsize 或者 array(fontface,fontsize)
  193. * @param string $type 图像格式 默认PNG
  194. * @param integer $disturb 是否干扰 1 点干扰 2 线干扰 3 复合干扰 0 无干扰
  195. * @param bool $border 是否加边框 array(color)
  196. * @return string
  197. */
  198. static function buildString($string, $rgb = array(), $filename = '', $type = 'png', $disturb = 1, $border = true) {
  199. if (is_string($size))
  200. $size = explode(',', $size);
  201. $width = $size[0];
  202. $height = $size[1];
  203. if (is_string($font))
  204. $font = explode(',', $font);
  205. $fontface = $font[0];
  206. $fontsize = $font[1];
  207. $length = strlen($string);
  208. $width = ($length * 9 + 10) > $width ? $length * 9 + 10 : $width;
  209. $height = 22;
  210. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  211. $im = @imagecreatetruecolor($width, $height);
  212. } else {
  213. $im = @imagecreate($width, $height);
  214. }
  215. if (empty($rgb)) {
  216. $color = imagecolorallocate($im, 102, 104, 104);
  217. } else {
  218. $color = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]);
  219. }
  220. $backColor = imagecolorallocate($im, 255, 255, 255); //背景色(随机)
  221. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  222. $pointColor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255)); //点颜色
  223. @imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
  224. @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  225. @imagestring($im, 5, 5, 3, $string, $color);
  226. if (!empty($disturb)) {
  227. // 添加干扰
  228. if ($disturb = 1 || $disturb = 3) {
  229. for ($i = 0; $i < 25; $i++) {
  230. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pointColor);
  231. }
  232. } elseif ($disturb = 2 || $disturb = 3) {
  233. for ($i = 0; $i < 10; $i++) {
  234. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $pointColor);
  235. }
  236. }
  237. }
  238. Image::output($im, $type, $filename);
  239. }
  240. /**
  241. * 生成图像验证码
  242. * @static
  243. * @access public
  244. * @param string $length 位数
  245. * @param string $mode 类型
  246. * @param string $type 图像格式
  247. * @param string $width 宽度
  248. * @param string $height 高度
  249. * @return string
  250. */
  251. static function buildImageVerify($length = 4, $mode = 1, $type = 'png', $width = 48, $height = 22, $verifyName = 'verify') {
  252. import('ORG.Util.String');
  253. $randval = String::randString($length, $mode);
  254. $_SESSION[$verifyName] = md5($randval);
  255. $width = ($length * 10 + 10) > $width ? $length * 10 + 10 : $width;
  256. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  257. $im = imagecreatetruecolor($width, $height);
  258. } else {
  259. $im = imagecreate($width, $height);
  260. }
  261. $r = Array(225, 255, 255, 223);
  262. $g = Array(225, 236, 237, 255);
  263. $b = Array(225, 236, 166, 125);
  264. $key = mt_rand(0, 3);
  265. $backColor = imagecolorallocate($im, $r[$key], $g[$key], $b[$key]); //背景色(随机)
  266. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  267. imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $backColor);
  268. imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  269. $stringColor = imagecolorallocate($im, mt_rand(0, 200), mt_rand(0, 120), mt_rand(0, 120));
  270. // 干扰
  271. for ($i = 0; $i < 10; $i++) {
  272. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $stringColor);
  273. }
  274. for ($i = 0; $i < 25; $i++) {
  275. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $stringColor);
  276. }
  277. for ($i = 0; $i < $length; $i++) {
  278. imagestring($im, 5, $i * 10 + 5, mt_rand(1, 8), $randval{$i}, $stringColor);
  279. }
  280. Image::output($im, $type);
  281. }
  282. // 中文验证码
  283. static function GBVerify($length = 4, $type = 'png', $width = 180, $height = 50, $fontface = 'simhei.ttf', $verifyName = 'verify') {
  284. import('ORG.Util.String');
  285. $code = String::randString($length, 4);
  286. $width = ($length * 45) > $width ? $length * 45 : $width;
  287. $_SESSION[$verifyName] = md5($code);
  288. $im = imagecreatetruecolor($width, $height);
  289. $borderColor = imagecolorallocate($im, 100, 100, 100); //边框色
  290. $bkcolor = imagecolorallocate($im, 250, 250, 250);
  291. imagefill($im, 0, 0, $bkcolor);
  292. @imagerectangle($im, 0, 0, $width - 1, $height - 1, $borderColor);
  293. // 干扰
  294. for ($i = 0; $i < 15; $i++) {
  295. $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  296. imagearc($im, mt_rand(-10, $width), mt_rand(-10, $height), mt_rand(30, 300), mt_rand(20, 200), 55, 44, $fontcolor);
  297. }
  298. for ($i = 0; $i < 255; $i++) {
  299. $fontcolor = imagecolorallocate($im, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
  300. imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $fontcolor);
  301. }
  302. if (!is_file($fontface)) {
  303. $fontface = dirname(__FILE__) . "/" . $fontface;
  304. }
  305. for ($i = 0; $i < $length; $i++) {
  306. $fontcolor = imagecolorallocate($im, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120)); //这样保证随机出来的颜色较深。
  307. $codex = String::msubstr($code, $i, 1);
  308. imagettftext($im, mt_rand(16, 20), mt_rand(-60, 60), 40 * $i + 20, mt_rand(30, 35), $fontcolor, $fontface, $codex);
  309. }
  310. Image::output($im, $type);
  311. }
  312. /**
  313. * 把图像转换成字符显示
  314. * @static
  315. * @access public
  316. * @param string $image 要显示的图像
  317. * @param string $type 图像类型,默认自动获取
  318. * @return string
  319. */
  320. static function showASCIIImg($image, $string = '', $type = '') {
  321. $info = Image::getImageInfo($image);
  322. if ($info !== false) {
  323. $type = empty($type) ? $info['type'] : $type;
  324. unset($info);
  325. // 载入原图
  326. $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
  327. $im = $createFun($image);
  328. $dx = imagesx($im);
  329. $dy = imagesy($im);
  330. $i = 0;
  331. $out = '<span style="padding:0px;margin:0;line-height:100%;font-size:1px;">';
  332. set_time_limit(0);
  333. for ($y = 0; $y < $dy; $y++) {
  334. for ($x = 0; $x < $dx; $x++) {
  335. $col = imagecolorat($im, $x, $y);
  336. $rgb = imagecolorsforindex($im, $col);
  337. $str = empty($string) ? '*' : $string[$i++];
  338. $out .= sprintf('<span style="margin:0px;color:#%02x%02x%02x">' . $str . '</span>', $rgb['red'], $rgb['green'], $rgb['blue']);
  339. }
  340. $out .= "<br>\n";
  341. }
  342. $out .= '</span>';
  343. imagedestroy($im);
  344. return $out;
  345. }
  346. return false;
  347. }
  348. /**
  349. * 生成UPC-A条形码
  350. * @static
  351. * @param string $type 图像格式
  352. * @param string $type 图像格式
  353. * @param string $lw 单元宽度
  354. * @param string $hi 条码高度
  355. * @return string
  356. */
  357. static function UPCA($code, $type = 'png', $lw = 2, $hi = 100) {
  358. static $Lencode = array('0001101', '0011001', '0010011', '0111101', '0100011',
  359. '0110001', '0101111', '0111011', '0110111', '0001011');
  360. static $Rencode = array('1110010', '1100110', '1101100', '1000010', '1011100',
  361. '1001110', '1010000', '1000100', '1001000', '1110100');
  362. $ends = '101';
  363. $center = '01010';
  364. /* UPC-A Must be 11 digits, we compute the checksum. */
  365. if (strlen($code) != 11) {
  366. die("UPC-A Must be 11 digits.");
  367. }
  368. /* Compute the EAN-13 Checksum digit */
  369. $ncode = '0' . $code;
  370. $even = 0;
  371. $odd = 0;
  372. for ($x = 0; $x < 12; $x++) {
  373. if ($x % 2) {
  374. $odd += $ncode[$x];
  375. } else {
  376. $even += $ncode[$x];
  377. }
  378. }
  379. $code.= ( 10 - (($odd * 3 + $even) % 10)) % 10;
  380. /* Create the bar encoding using a binary string */
  381. $bars = $ends;
  382. $bars.=$Lencode[$code[0]];
  383. for ($x = 1; $x < 6; $x++) {
  384. $bars.=$Lencode[$code[$x]];
  385. }
  386. $bars.=$center;
  387. for ($x = 6; $x < 12; $x++) {
  388. $bars.=$Rencode[$code[$x]];
  389. }
  390. $bars.=$ends;
  391. /* Generate the Barcode Image */
  392. if ($type != 'gif' && function_exists('imagecreatetruecolor')) {
  393. $im = imagecreatetruecolor($lw * 95 + 30, $hi + 30);
  394. } else {
  395. $im = imagecreate($lw * 95 + 30, $hi + 30);
  396. }
  397. $fg = ImageColorAllocate($im, 0, 0, 0);
  398. $bg = ImageColorAllocate($im, 255, 255, 255);
  399. ImageFilledRectangle($im, 0, 0, $lw * 95 + 30, $hi + 30, $bg);
  400. $shift = 10;
  401. for ($x = 0; $x < strlen($bars); $x++) {
  402. if (($x < 10) || ($x >= 45 && $x < 50) || ($x >= 85)) {
  403. $sh = 10;
  404. } else {
  405. $sh = 0;
  406. }
  407. if ($bars[$x] == '1') {
  408. $color = $fg;
  409. } else {
  410. $color = $bg;
  411. }
  412. ImageFilledRectangle($im, ($x * $lw) + 15, 5, ($x + 1) * $lw + 14, $hi + 5 + $sh, $color);
  413. }
  414. /* Add the Human Readable Label */
  415. ImageString($im, 4, 5, $hi - 5, $code[0], $fg);
  416. for ($x = 0; $x < 5; $x++) {
  417. ImageString($im, 5, $lw * (13 + $x * 6) + 15, $hi + 5, $code[$x + 1], $fg);
  418. ImageString($im, 5, $lw * (53 + $x * 6) + 15, $hi + 5, $code[$x + 6], $fg);
  419. }
  420. ImageString($im, 4, $lw * 95 + 17, $hi - 5, $code[11], $fg);
  421. /* Output the Header and Content. */
  422. Image::output($im, $type);
  423. }
  424. static function output($im, $type = 'png', $filename = '') {
  425. header("Content-type: image/" . $type);
  426. $ImageFun = 'image' . $type;
  427. if (empty($filename)) {
  428. $ImageFun($im);
  429. } else {
  430. $ImageFun($im, $filename);
  431. }
  432. imagedestroy($im);
  433. }

发表评论

表情:
评论列表 (有 0 条评论,557人围观)

还没有评论,来说两句吧...

相关阅读

    相关 图片验证

    1、验证码的作用: (1)防止攻击者恶意攻击、反复登录。 (2)通过字符的模糊处理(倾斜、干扰线),攻击者很难扫描到验证码的具体内容,但是人可以很容易辨认包含的内容并进行登

    相关 验证图片

    作者:吱韩菌 开发工具:Visual Studio 2015 撰写时间:2019-6-27 在大部分软件中,登录和注册都会涉及到信息验证,而验证的方式也是琳琅满目,随