<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Cookie;
use app\components\AuthcodeHelper;

class VerifycodeController extends Controller{
	
	public function actionIndex(){
		$string = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9');
		$maxnum = rand(4,6); //随机4到6位
		//$maxnum = 4; //固定4位
		$verifycode = "";
		for($j=1;$j<=$maxnum;$j++){
			$k = rand(0, count($string)-1);
			$verifycode = $verifycode . $string[$k];
		}
		$cookiekey = Yii::$app->params["verify_cookiekey"];
		$cookiename = Yii::$app->params["verify_cookiename"];
		$cookievalue = strtolower($verifycode);
		$cookievalue = AuthcodeHelper::authcode($cookievalue, "", $cookiekey, 0);
		$cookie = new Cookie();
		$cookie->name = $cookiename;
		$cookie->value = $cookievalue;
		Yii::$app->response->cookies->add($cookie);
		ob_clean();
		header('Pragma: public'); 
		header('Expires: 0');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
		header('Content-Transfer-Encoding: binary');
		header("Content-type: image/png");
		$im = imagecreatetruecolor(65, 20);
		/*$bgcolor = imagecolorallocate($im,255,255,255);
		imagefill($im,0,0,$bgcolor);
		$bgcolortrans = imagecolortransparent($im,$bgcolor);
		imagealphablending($im, false);
		imagesavealpha($im, true);*/
		$white = imagecolorallocate($im, 255,255,255);
		$black = imagecolorallocate($im, 30,30,30);
		$gray  = imagecolorallocate($im, 200,200,200); 
		imagefill($im,0,0,$white);
		//绘制边框
		/*$bordercolor = imagecolorallocate($im, 0, 0, 127);
		$this->drawBorder($im,$bordercolor, 1);*/
		$textcolor = imagecolorallocate($im, 255, 0, 0);
		$size   = 16;
		$px     = 5;
		$py     = 2;
		imagestring($im, $size, $px, $py, $verifycode, $textcolor);
		//加入3条干扰线;也可以不要;视情况而定，因为可能影响用户输入 
		/*$li = imagecolorallocate($im, 220,220,220);
		for($i=0;$i<3;$i++)
		{
			imageline($im,rand(0,30),rand(0,21),rand(20,40),rand(0,21),$li);
		}*/
		//加入干扰象素
		/*for($i=0;$i<80;$i++)
		{
			imagesetpixel($im, rand()%70 , rand()%30 , $black);
		}*/
		imagepng($im);
		imagedestroy($im);
	}
	
	//绘制边框
	//usage:
	//$color = imagecolorallocate($img, 255, 0, 0);
	//drawBorder($img,$color, 1);
	public function drawBorder(&$img, &$color, $thickness = 1){
		$x1 = 0;
		$y1 = 0;
		$x2 = imagesx($img) - 1;
		$y2 = imagesy($img) - 1;
		for($i = 0; $i < $thickness; $i++){
			imagerectangle($img, $x1++, $y1++, $x2--, $y2--, $color);
		}
	}
	
}
?>