Generates a captcha image.

@param integer width Image width.
@param integer height Image height.
@param integer characters String length.

@throws \Exception Problem with GD.

@return Ressource Image ressource.

@api
438831
public static function image($width='120', $height='40', $characters='6') {
		$font = __DIR__.'/../'.static::$font;

		$code = static::generateCode($characters);
		#todo, utiliser comme service?
		\Asgard\Container\Container::singleton()['httpKernel']->getRequest()->session->set('captcha', $code);
		/* font size will be 75% of the image height */
		$font_size = $height * 0.75;
		if(!$image = imagecreate($width, $height))
			throw new Exception('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 20, 40, 100);
		$noise_color = imagecolorallocate($image, 100, 120, 180);
		/* generate random dots in background */
		for($i=0; $i<($width*$height)/3; $i++)
			imagefilledellipse($image, mt_rand(0, $width), mt_rand(0, $height), 1, 1, $noise_color);
		/* generate random lines in background */
		for( $i=0; $i<($width*$height)/150; $i++ )
			imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $noise_color);
		/* create textbox and add text */
		if(!$textbox = imagettfbbox($font_size, 0, $font, $code))
			throw new Exception('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		if(!imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code))
			throw new Exception('Error in imagettftext function');
		return $image;
	}
842601
public static function saveCaptcha($value, $localFile, $width = 200, $height = 100, $quality = 100)
    {
        $builder = new CaptchaBuilder($value);
        $builder->setTextColor(self::$textColor[0], self::$textColor[1], self::$textColor[2]);
        $builder->setBackgroundColor(self::$backgroundColor[0], self::$backgroundColor[1], self::$backgroundColor[2]);
        $builder->build($width, $height, self::$captchaFont ? self::$captchaFont : null);
        return $builder->save($localFile, $quality);
    }
909497
public static CircleCaptcha createCircleCaptcha(int width, int height, int codeCount, int circleCount) {
		return new CircleCaptcha(width, height, codeCount, circleCount);
	}
2208
public T createImage( int width , int height ) {
		switch( family ) {
			case GRAY:
				return (T)GeneralizedImageOps.createSingleBand(getImageClass(),width,height);

			case INTERLEAVED:
				return (T)GeneralizedImageOps.createInterleaved(getImageClass(), width, height, numBands);

			case PLANAR:
				return (T)new Planar(getImageClass(),width,height,numBands);

			default:
				throw new IllegalArgumentException("Type not yet supported");
		}
	}
961589
public function actionImageResize() {
		$source = $this->getSource();

		$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getPath());

		$info = $this->getImageEditorInfo();

		if (!$info->box || (int)$info->box->w <= 0) {
			throw new \Exception('Width not specified', Consts::ERROR_CODE_BAD_REQUEST);
		}

		if (!$info->box || (int)$info->box->h <= 0) {
			throw new \Exception('Height not specified', Consts::ERROR_CODE_BAD_REQUEST);
		}


		$info->img
			->resize((int)$info->box->w, (int)$info->box->h)
			->save($info->path . $info->newname, $source->quality);
	}
574665
public function drawChar()
    {
        $x = ($this->width - 10) / $this->charNum;
        $captchaStr = '';//保存产生的字符串

        for ($i = 0; $i < $this->charNum; $i++) {
            $char = $this->codeStr[random_int(0, \strlen($this->codeStr) - 1)];
            $captchaStr .= $char;
            $fontColor = imagecolorallocate($this->img, random_int(80, 200), random_int(80, 200), random_int(80, 200));
            imagefttext(
                $this->img, $this->fontSize, random_int(-30, 30), $i * $x + random_int(6, 10),
                random_int($this->height / 1.3, $this->height - 5), $fontColor,
                $this->font, $char
            );
        }

        $this->captcha = strtolower($captchaStr);

        //把纯的验证码字符串放置到SESSION中进行保存，便于后面进行验证对比
        $_SESSION[static::$sessionKey] = md5($this->captcha);

        //设置cookie到前端浏览器，可用于前端验证
        setcookie(static::$sessionKey, md5($this->captcha));
    }
869563
protected function renderImage()
	{
		if(!isset($this->imageOptions['id']))
			$this->imageOptions['id']=$this->getId();

		$url=$this->getController()->createUrl($this->captchaAction,array('v'=>uniqid()));
		$alt=isset($this->imageOptions['alt'])?$this->imageOptions['alt']:'';
		echo CHtml::image($url,$alt,$this->imageOptions);
	}
320075
public static LineCaptcha createLineCaptcha(int width, int height, int codeCount, int lineCount) {
		return new LineCaptcha(width, height, codeCount, lineCount);
	}
1041533
public function html()
    {
        if (!$this->getPublicKey()) {
            throw new Exception('You must set public key provided by reCaptcha');
        }

        $error = ($this->getError() ? '&amp;error=' . $this->getError() : null);

        $theme = null;

        // If user specified a reCaptcha theme, output it as one of the options
        if ($this->theme) {
            $theme = '<script> var RecaptchaOptions = {theme: "' . $this->theme . '"};</script>';
        }

        return $theme . '<script type="text/javascript" src="' . self::SERVER . '/challenge?k=' . $this->getPublicKey() . $error . '"></script>

        <noscript>
            <iframe src="' . self::SERVER . '/noscript?k=' . $this->getPublicKey() . $error . '" height="300" width="500" frameborder="0"></iframe><br/>
            <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
            <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
        </noscript>';
    }
109046
function asGDImage($text,$resize=160){
        $barcode = $this->encode($text);
        $w  = $barcode['width'];
        $h  = $barcode['height'];
        $bs = 10;
        $size  = $bs * $w;

        $img   = imagecreatetruecolor($size + 2 * $bs * 2 ,$size + 2 * $bs * 2);
        $white = imagecolorallocate($img,255,255,255);
        $black = imagecolorallocate($img,0,0,0);
        imagefill($img,0,0,$white);

        for($j=0; $j < $h; $j++){
            for($i=0; $i < $w; $i++){
                $x1 = ($i * $bs) + $bs * 2;
                $y1 = ($size - (($j + 1) * $bs)) + $bs * 2;
                $x2 = $x1 + $bs;
                $y2 = $y1 + $bs;

                if($barcode['data'][$j * $w + $i]){
                    imagefilledrectangle($img,$x1,$y1,$x2,$y2,$black);
                } else {
                    imagefilledrectangle($img,$x1,$y1,$x2,$y2,$white);
                }
            }
        }

        if($resize == $size){
            return $img;
        }

        $new  = imagecreatetruecolor($resize,$resize);
        imagecopyresized($new, $img, 0, 0, 0, 0, $resize, $resize, $size + 2 * $bs * 2, $size + 2 * $bs * 2);
        imagedestroy($img);
        return $new;
    }
757876
public function apply($resource){
		// Extract arguments
		@list(,$x,$y,$width,$height)=func_get_args();
		$x=(int)$x;
		$y=(int)$y;
		$width=(int)$width;
		$height=(int)$height;
		// Get resolution
		$w_src=imagesx($resource);
		$h_src=imagesy($resource);
		if($w_src===false || $h_src===false){
			throw new Exception("An error was encountered while getting source image resolution");
		}
		// Verifications
		if(!$width || !$height){
			throw new Exception("Invalid image resolution provided");
		}
		if(($x+$width)>$w_src || ($y+$height)>$h_src){
			throw new Exception("Dimensions provided seems to be out of the image resolution");
		}
		// Create new image
		$image=$this->_createTrueColor($width,$height);
		// Cut image
		if(!imagecopy($image,$resource,0,0,$x,$y,$width,$height)){
			throw new Exception("Failed to copy image portion");
		}
		return $image;
	}
564521
public function resize($width, $height) {
        if (!$width) $width = 1;
        if (!$height) $height = 1;
        return (
            (false !== ($img = new gd(array($width, $height)))) &&
            $img->imagecopyresampled($this) &&
            (false !== ($this->image = $img->get_image())) &&
            (false !== ($this->width = $img->get_width())) &&
            (false !== ($this->height = $img->get_height()))
        );
    }
385317
private function getCaptchaImage()
    {
        $image = $this->client->get(self::URL_CAPTCHA);

        if (false === $image) {
            $this->error = 'No se pudo cargar el captcha image';

            return false;
        }

        return $image;
    }
1055223
public function createThumbnail($width, $height, $prefix = 'thumb_') {
		//imagecreatefromjpeg may run out of memory and cause a fatal error, check if image will fit in memory before processing
		$this->checkMemory();
		
		//determine image type
	 	$imagetype = exif_imagetype($this->dir . $this->filename);
	 	if($imagetype == IMAGETYPE_JPEG) {
	 		$srcImg = imagecreatefromjpeg($this->dir . $this->filename);	
	 	} else if($imagetype == IMAGETYPE_GIF) {
	 		$srcImg = imagecreatefromgif($this->dir . $this->filename);
	 	} else if($imagetype == IMAGETYPE_PNG) {
	 		$srcImg = imagecreatefrompng($this->dir . $this->filename);
	 	} else {
	 		throw new Exception('Unsupported imagetype code ' . $imagetype);
	 	}
	 	
	 	//determine thumbnail size keeping aspect ratio
	 	$old_x=imageSX($srcImg);
		$old_y=imageSY($srcImg);
		
		if ($height > $old_y) {
			$height = $old_y;
			$width = $old_y;
		}
		if ($width > $old_x) {
			$width = $old_x;
			$height = $old_x;
		}
		
		if ($this->defaultDimension == 'height') {
			$thumb_w = $old_x*($width/$old_y);
			$thumb_h = $height;
		} else if ($this->defaultDimension == 'width') {
			$thumb_w = $width;
			$thumb_h = $old_y*($height/$old_x);
		} else {
			if ($old_x > $old_y) {
				$thumb_w = $width;
				$thumb_h = $old_y*($height/$old_x);
			} else if ($old_x < $old_y) {
				$thumb_w = $old_x*($width/$old_y);
				$thumb_h = $height;
			} else if ($old_x == $old_y) {
				$thumb_w = $width;
				$thumb_h = $height;
			}
		}
		
		//create image resource
		if($imagetype != IMAGETYPE_GIF) {
			$dstImg = ImageCreateTrueColor($thumb_w, $thumb_h);
		} else {
			$dstImg = imagecreate($thumb_w, $thumb_h);
		}
		
		//preserve transparency for png
		if($imagetype == IMAGETYPE_PNG) {
			imagealphablending($dstImg, false);
			imagesavealpha($dstImg, true);
		} else if($imagetype == IMAGETYPE_GIF) {
			imagecolorallocate($dstImg, 255, 255, 255);
		}
		
		imagecopyresampled($dstImg,$srcImg,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
		
		$thumbName = $this->createThumbName($this->filename, $prefix);
		
		if($imagetype == IMAGETYPE_PNG) {
			imagepng($dstImg, $this->dir . $thumbName, 4);
		} else if($imagetype == IMAGETYPE_GIF) {
			imagegif($dstImg, $this->dir . $thumbName);	 
		} else {
			imagejpeg($dstImg, $this->dir . $thumbName, 100);
		}	
	
		imagedestroy($dstImg);
		imagedestroy($srcImg);
		
		return $thumbName;
	}
479769
static function createImage( $width, $height, &$useTruecolor )
    {
        if ( $useTruecolor === null )
        {
//             print( "has GD2='" . eZImageInterface::hasGD2() . "'<br/>" );
            $useTruecolor = eZImageInterface::hasGD2();
        }
        if ( $useTruecolor and
             !function_exists( 'ImageCreateTrueColor' ) )
        {
            eZDebug::writeWarning( 'Function ImageCreateTrueColor does not exist, cannot create true color images', __METHOD__ );
            $useTruecolor = false;
        }
        if ( $useTruecolor )
            $imageObject = ImageCreateTrueColor( $width, $height );
        else
            $imageObject = ImageCreate( $width, $height );
        return $imageObject;
    }
698986
public function create($width = null, $height = null)
    {
        $this->width  = ($width)  ? $width : $this->width;
        $this->height = ($height) ? $height : $this->height;

        $imageType    = $this->getImageType();
        $createFunc   = ($imageType === 'gif') ? 'imagecreate' : 'imagecreatetruecolor';
        $this->image  = $createFunc($this->width, $this->height);

        $bgColor = $this->backgroundColor;

        $backgroundColor = imagecolorallocate($this->image, $bgColor[0], $bgColor[1], $bgColor[2]);

        imagefilledrectangle($this->image, 0, 0, $this->width, $this->height, $backgroundColor);

        $this->drawText();

        if ($this->drawBorder)
        {
            $this->drawBorder();
        }

        if ($this->drawLine)
        {
            $this->drawLine();
        }

        if ($this->drawPixel)
        {
            $this->drawPixel();
        }

        return $this;
    }
287259
protected function doImage()
    {
        if($this->use_transparent_text == true || $this->bgimg != '' || function_exists('imagecreatetruecolor')) {
            $imagecreate = 'imagecreatetruecolor';
        } else {
            $imagecreate = 'imagecreate';
        }

        $this->im = $imagecreate($this->image_width, $this->image_height);

        if (function_exists('imageantialias')) {
            imageantialias($this->im, true);
        }

        $this->allocateColors();

        if ($this->perturbation > 0) {
            $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale);
            imagepalettecopy($this->tmpimg, $this->im);
        } else {
            $this->iscale = 1;
        }

        $this->setBackground();

        $code = '';

        if ($this->getCaptchaId(false) !== null) {
            // a captcha Id was supplied

            // check to see if a display_value for the captcha image was set
            if (is_string($this->display_value) && strlen($this->display_value) > 0) {
                $this->code_display = $this->display_value;
                $this->code         = ($this->case_sensitive) ?
                                       $this->display_value   :
                                       strtolower($this->display_value);
                $code = $this->code;
            } elseif ($this->openDatabase()) {
                // no display_value, check the database for existing captchaId
                $code = $this->getCodeFromDatabase();

                // got back a result from the database with a valid code for captchaId
                if (is_array($code)) {
                    $this->code         = $code['code'];
                    $this->code_display = $code['code_disp'];
                    $code = $code['code'];
                }
            }
        }

        if ($code == '') {
            // if the code was not set using display_value or was not found in
            // the database, create a new code
            $this->createCode();
        }

        if ($this->noise_level > 0) {
            $this->drawNoise();
        }

        $this->drawWord();

        if ($this->perturbation > 0 && is_readable($this->ttf_file)) {
            $this->distortedCopy();
        }

        if ($this->num_lines > 0) {
            $this->drawLines();
        }

        if (trim($this->image_signature) != '') {
            $this->addSignature();
        }

        $this->output();
    }