/** * Creates an image for every code character. */ protected function createCharImages() { $counter = 0; for ($i = 0, $j = strlen($this->codeWord); $i < $j; $i++) { $char = $this->codeWord[$i]; $tempImageWidth = $this->fontSize * 2; $tempImageHeight = $this->fontSize + 40; // create image $tempImage = imageCreate($tempImageWidth, $tempImageHeight); $tempColor = imageColorAllocate($tempImage, $this->color2['red'], $this->color2['green'], $this->color2['blue']); imageColorTransparent($tempImage, $tempColor); // set font color $fontColor = imageColorAllocate($tempImage, $this->fontColor['red'], $this->fontColor['green'], $this->fontColor['blue']); // write text imageTtfText($tempImage, $this->fontSize, 0, 10, $this->fontSize + mt_rand(25, 30), $fontColor, $this->fontFace, $char); // morph text if (CAPTCHA_FONT_MORPH) { $tempImageHeight = 120; $tempImage2 = imageCreate($tempImageWidth, 120); $tempColor = imageColorAllocate($tempImage2, $this->color2['red'], $this->color2['green'], $this->color2['blue']); imageColorTransparent($tempImage2, $tempColor); $divisor = mt_rand(6, 7); $quotient = mt_rand(4, 6); $method = mt_rand(0, 1); // morph text on x-axis if ($method == 0) { for ($y = 1; $y <= $tempImageHeight; $y++) { $posX = sin($y / $divisor) * $quotient; imageCopyMerge($tempImage2, $tempImage, $posX, $y, 0, $y, $tempImageWidth, 1, 100); } } // morph text on y-axis if ($method == 1) { for ($x = 1; $x <= $tempImageWidth; $x++) { $posY = sin($x / $divisor) * $quotient; imageCopyMerge($tempImage2, $tempImage, $x, $posY, $x, 0, 1, $tempImageHeight, 100); } } $image = $tempImage2; } else { $image = $tempImage; } // get text width and height $positionX = 0; for ($x = $tempImageWidth - 1; $x > 0; $x--) { for ($y = $tempImageHeight - 1; $y > 0; $y--) { $color = imageColorAt($image, $x, $y); $colorArray = imageColorsForIndex($image, $color); if ($colorArray['red'] == $this->fontColor['red'] && $colorArray['green'] == $this->fontColor['green'] && $colorArray['blue'] == $this->fontColor['blue']) { $positionX = $x; $x = 0; $y = 0; break; } } } $width = $positionX + 10; $height = 100; // create final char image $this->chars[$counter] = imageCreate($width, $height); $color2 = imageColorAllocate($this->chars[$counter], $this->color2['red'], $this->color2['green'], $this->color2['blue']); imageColorTransparent($this->chars[$counter], $color2); imageCopyMerge($this->chars[$counter], $image, 5, 5, 0, 0, $width, $tempImageHeight, 100); $this->charWidth[$counter] = $width; // destroy temp images imageDestroy($tempImage); if (CAPTCHA_FONT_MORPH) { imageDestroy($tempImage2); } $counter++; } }
$charImageStep = $imageWidth / ($charsNumber + 1); $charWritePoint = $charImageStep; // Write captcha characters to the image for ($i = 0; $i < $charsNumber; $i++) { $nextChar = $characters[mt_rand(0, count($characters) - 1)]; $captchaText .= $nextChar; // Font properties $randomFontSize = mt_rand(25, 30); // Random character size to spice things a little bit :) $randomFontAngle = mt_rand(-25, 25); // Twist the character a little bit $fontType = select_captcha_font(); // This is the font we are using - we need to point to the ttf file here // Pixels $pixelX = $charWritePoint; // We will write a character at this X point $pixelY = 40; // We will write a character at this Y point // Random character color // R // G // B // Alpha $randomCharColor = imageColorAllocateAlpha($captchaImage, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 25)); // Write a character to the image imageTtfText($captchaImage, $randomFontSize, $randomFontAngle, $pixelX, $pixelY, $randomCharColor, $fontType, $nextChar); // Increase captcha step $charWritePoint += $charImageStep; } // Add currently generated captcha text to the session $_SESSION['login_captcha'] = $captchaText; // Return the image return imagePng($captchaImage); // Destroy captcha image imageDestroy($captchaImage);
require_once JPATH_BASE . DS . 'includes' . DS . 'framework.php'; $app = JFactory::getApplication('site')->initialise(); //Фон для капчи $im = imageCreateTrueColor(110, 30); $color = imageColorAllocate($im, 218, 218, 218); imageFill($im, 10, 10, $color); $color = imageColorAllocate($im, 153, 153, 153); for ($i = 0; $i < 800; $i++) { $randW = mt_rand(0, imageSX($im)); $randH = mt_rand(0, imageSY($im)); imageSetPixel($im, $randW, $randH, $color); } //Текст для капчи $color = imageColorAllocate($im, 0, 0, 0); $str = "ABCDEFGHJKLMNPKASTUVWXYZ"; $degrees = array(10, -10, 15, 0, -20); $rands = array(mt_rand(0, 7), mt_rand(0, 9), mt_rand(8, 15), mt_rand(0, 9), mt_rand(16, 23)); $opts = array(mt_rand(2, 8), mt_rand(22, 26), mt_rand(46, 50), mt_rand(70, 72), mt_rand(86, 88)); for ($i = 0; $i < 5; $i++) { $nt = $str[$rands[$i]]; $n .= $nt; imageTtfText($im, 16, $degrees[$i], $opts[$i], mt_rand(18, 26), $color, "font/arl.ttf", $nt); } $emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1)); imageconvolution($im, $emboss, 1, 128); //Пишем текст в сессию $session = JFactory::getSession(); $session->set('mycap', md5(strtolower($n))); header("Content-type: image/jpeg"); imageJpeg($im); imageDestroy($im);
$i = imageCreateTrueColor(500, 300); /* Подготовка к работе */ imageAntiAlias($i, true); $red = imageColorAllocate($i, 255, 0, 0); $white = imageColorAllocate($i, 0xff, 0xff, 0xff); $black = imageColorAllocate($i, 0, 0, 0); $green = imageColorAllocate($i, 0, 255, 0); $blue = imageColorAllocate($i, 0, 0, 255); $grey = imageColorAllocate($i, 192, 192, 192); imageFill($i, 0, 0, $grey); /* Рисуем примитивы */ imageSetPixel($i, 10, 10, $black); imageLine($i, 20, 20, 280, 180, $red); imageRectangle($i, 20, 20, 280, 180, $blue); //array of dots $points = [120, 120, 100, 200, 300, 200]; imagePolygon($i, $points, 3, $green); imageEllipse($i, 200, 150, 300, 200, $red); // imageArc($i, 210, 160, 300, 200, 0, 90, $black); imageFilledArc($i, 200, 150, 300, 200, 0, 40, $red, IMG_ARC_PIE); /* Рисуем текст */ imageString($i, 5, 150, 200, 'php7', $black); imageCharUp($i, 3, 200, 200, 'PHP5', $blue); imageTtfText($i, 30, 10, 300, 150, $green, 'arial.ttf', 'PHP7'); /* Отдаем изображение */ // header("Content-type: image/gif"); // imageGif($i); header("Content-type: image/png"); imagePng($i); //header("Content-type: image/jpg"); //imageJpeg($i);
<?php //$img = imageCreateTrueColor(500,300); $img = imagecreatefromjpeg("images/noise.jpg"); imageAntiAlias($img, true); //зглаживание $red = imageColorAllocate($img, 255, 0, 0); $green = imageColorAllocate($img, 0, 255, 0); $blue = imageColorAllocate($img, 0, 0, 255); $white = imageColorAllocate($img, 255, 255, 255); $black = imageColorAllocate($img, 0, 0, 0); $silver = imageColorAllocate($img, 192, 192, 192); /* imageLine($img,20,20,480,280,$white); imageLine($img,480,20,20,280,$red); imageFilledRectangle($img,40,40,80,280,$white); imageRectangle($img,20,20,80,280,$blue); $points = array(0,0,100,200,300,200); imagePolygon($img, $points,3,$green); imageEllipse($img, 200,150,300,200, $red); imageFilledEllipse($img, 200,150,300,200, $red); imageArc($img, 210,160,300,200,0,-60, $blue); imageFilledArc($img, 210,160,300,200,0,90, $silver, IMG_ARC_NOFILL); imageString($img, 5, 150, 200, "Hello!", $white); imageTtfText($img,30,10,200,150,$red,"arial.ttf","Привет!"); */ imageTtfText($img, 20, 3, 20, 30, $black, "arial.ttf", "Привет"); header('Content-type: image/png'); imagePNG($img);
/** * Draws and returns the height of the title and its padding (in pixels). If no title is * specified, then nothing is drawn and 0 is returned. * @var float x location * @var float y location * @return int The height of the title + padding. */ protected function _drawTitle($x = 0, $y = 0) { if (!$this->title) { return 0; } $titleColor = $this->_convertColor($this->textColor); // Determine ideal font size for the title. $titleSize = 0.0675 * $this->height; // The largest sensible value. $minTitleSize = 10; // The smallest legible value. do { $titleBBox = imageTTFBBox($titleSize, 0, $this->titleFont, $this->title); $titleWidth = $titleBBox[2] - $titleBBox[0]; // If we can fit the title in, with 5% padding on each side, then we can // draw it. if ($titleWidth <= $this->width * 0.9) { break; } $titleSize -= 0.5; // Try a smaller font size. } while ($titleSize >= $minTitleSize); // If the title is simply too long to be drawn legibly, then we will simply not // draw it. if ($titleSize < $minTitleSize) { return 0; } $titleHeight = abs($titleBBox[7] - $titleBBox[1]); // Give the title 7.5% top padding. $titleTopPadding = 0.075 * $this->height; // Centre the title. $x = $this->width / 2 - $titleWidth / 2; $y = $titleTopPadding; imageTtfText($this->canvas, $titleSize, 0, $x + abs($titleBBox[0]), $y + abs($titleBBox[7]), $titleColor, $this->titleFont, $this->title); return $titleHeight + $titleTopPadding; }
<?php session_start(); function randString() { $nChars = 5; $string = "1234567890ABCDEFGHIJKLMNPQRSTUVWXYZ"; $result = ""; while (strlen($result) != $nChars) { $result .= substr(str_shuffle($string), rand(0, strlen($string)), 1); } return $result; } $_SESSION["captcha"] = $string = randString(); $img = imageCreateFromJPEG("noise.jpg"); imageAntiAlias($img, true); $colors = array($yellow = imageColorAllocate($img, 70, 70, 0), $red = imageColorAllocate($img, 255, 0, 0), $green = imageColorAllocate($img, 13, 153, 40), $blue = imageColorAllocate($img, 0, 0, 255)); for ($i = 0; $i < strlen($string); $i++) { imageTtfText($img, 25, rand(0, 50), 10 + 30 * ($i + 1), 35, $colors[rand(0, 3)], "georgia.ttf", $string[$i]); } header("Content-type: image/jpg"); imageJPEG($img, null, 90);
function GenerateThumbnail($src, $dst, $mw, $mh, $alwaysResize = false) { $size = @getImageSize($src); if (!$size || !($size[2] == 1 || $size[2] == 2 || $size[2] == 3)) { return false; } switch ($size[2]) { case 1: $type = 'gif'; break; case 2: $type = 'jpeg'; break; case 3: $type = 'png'; break; } if (isset($type)) { switch ($type) { case 'jpeg': $sim = imageCreateFromJPEG($src); break; case 'gif': $sim = imageCreateFromGIF($src); break; case 'png': $sim = imageCreateFromPNG($src); break; } if ($mw <= 0 || $mh <= 0) { $tw = $size[0]; $th = $size[1]; } elseif ($size[0] > $mw || $size[1] > $mh || $alwaysResize) { $ratio = $size[0] > $size[1] ? $size[0] / $mw : $size[1] / $mh; $tw = $size[0] / $ratio; $th = $size[1] / $ratio; } else { $tw = $size[0]; $th = $size[1]; } $text = $size[0] . 'x' . $size[1] . ' - ' . intval(filesize($src) / 1024) . 'Kb'; $font = BASE_PATH . 'incl/serifan.ttf'; $fontsize = 12 + 1; $fontangle = 0; do { $fontsize--; $bounds = imageTtfBBox($fontsize, $fontangle, $font, $text); } while ($fontsize > 6 && abs($bounds[0] - $bounds[2]) > $tw); $tha = 6 + abs($bounds[1] - $bounds[7]); $thumb = imageCreateTrueColor($tw, $th + $tha); imageCopyResampled($thumb, $sim, 0, 0, 0, 0, $tw, $th, $size[0], $size[1]); $th += $tha; $black = imageColorAllocate($thumb, 0, 0, 0); $white = imageColorAllocate($thumb, 255, 255, 255); $GLOBALS['image_orig_width'] = $size[0]; $GLOBALS['image_orig_height'] = $size[1]; $GLOBALS['image_thumb_width'] = $tw; $GLOBALS['image_thumb_height'] = $th; imageFilledRectangle($thumb, 0, $th - $tha, $tw - 1, $th - 1, $black); imageTtfText($thumb, $fontsize, $fontangle, $tw / 2 - $bounds[2] / 2, $th - 4 - $bounds[3], $white, $font, $text); imageRectangle($thumb, 0, 0, $tw - 1, $th - 1, $black); switch ($type) { case 'jpeg': imageJPEG($thumb, $dst); break; case 'gif': imageGIF($thumb, $dst); break; case 'png': imagePNG($thumb, $dst); break; } return true; } return false; }
<?php /*РАБОТА С ИЗОБРАЖЕНИЯМИ.ЧАСТЬ 3 урок 2-13 Функция iconv("CP1251","UTF-8",$string_1) - конвертирует строку из одной кодировки в другую */ $im = imageCreateTrueColor(400, 500); $color = imageColorAllocate($im, 0, 0, 0); imageFill($im, 100, 100, $color); $color = imageColorAllocate($im, 255, 255, 255); $string_1 = "Тестовая строка"; $string_1 = iconv("CP1251", "UTF-8", $string_1); imageTtfText($im, 20, 0, 10, 190, $color, "VERDANA.TTF", $string_1); header("Content-type: image/png"); imagePng($im); imageDestroy($im);
$nChars = 5; //количество символов на картинке $_SESSION['randStr'] = ''; for ($i = 0; $i < $nChars; ++$i) { $rand_sym = rand(0, 15); //выбранный случайный символ из массива символо $arr_sym $rand_str .= $arr_sym[$rand_sym]; $ang = rand(-5, 20); } $_SESSION['randStr'] = $rand_str; $res_str = $_SESSION['randStr']; $img = imagecreatefromjpeg("images/noise.jpg"); imageAntiAlias($img, true); //зглаживание $red = imageColorAllocate($img, 255, 0, 0); imageTtfText($img, 20, 10, 80, 30, $black, "arial.ttf", $res_str); header('Content-type: image/jpg'); imageJPEG($img); /* ЗАДАНИЕ 1 - Запустите сессию - Создайте переменную nChars(количество выводимых на картинке символов) и присвойте ей произвольное значение(рекомендуемое: 5) - Сгенерируйте случайную строку длиной nChars символов - Создайте сессионную переменную randStr и присвойте ей сгенерированную строку */ /* ЗАДАНИЕ 2 - Создайте изображение на основе файла "images/noise.jpg" - Создайте цвет для рисования - Включите сглаживание
<?php ## Пример работы с TTF-шрифтом. require_once "lib/imagettf.php"; // Выводимая строка. $string = "Привет, мир!"; // Шрифт. $font = getcwd() . "/times.ttf"; // Загружаем фоновой рисунок. $im = imageCreateFromPng("sample02.png"); // Угол поворота зависит от текущего времени. $angle = microtime(true) * 10 % 360; // Ксли хотите, чтобы текст шел из угла в угол, раскомментируйте строчку: # $angle = rad2deg(atan2(imageSY($im), imageSX($im))); // Подгоняем размер текста под размер изображения. $size = imageTtfGetMaxSize($angle, $font, $string, imageSX($im), imageSY($im)); // Создаем в палитре новые цвета $shadow = imageColorAllocate($im, 0, 0, 0); $color = imageColorAllocate($im, 128, 255, 0); // Вычисляем координаты вывода, чтобы текст оказался в центре. $sz = imageTtfSize($size, $angle, $font, $string); $x = (imageSX($im) - $sz[0]) / 2 + $sz[2]; $y = (imageSY($im) - $sz[1]) / 2 + $sz[3]; // Рисуем строку текста, вначале черным со сдвигом, а затем - // основным цветом поверх (чтобы создать эффект тени). imageTtfText($im, $size, $angle, $x + 3, $y + 2, $shadow, $font, $string); imageTtfText($im, $size, $angle, $x, $y, $color, $font, $string); // Сообщаем о том, что далее следует рисунок PNG. Header("Content-type: image/png"); // Выводим рисунок imagePng($im);
$j=0; while(++$j<3) imageFilledArc($i, rand(200,400), rand(100,200), rand(50,150), rand(50,100), rand(0,270), rand(0,270), $white,IMG_ARC_EDGED); */ /* $poll = []; $max = rand(10,20); for ($j=1; $j <= $max; $j++) { $poll[$j] = rand(200,800); } //$poll = array(10,34,52,4,18,96); $sum = array_sum($poll); $first = 0; foreach($poll as &$value) { $value /= $sum; $color = imageColorAllocate($i,rand(100,250), rand(100,250), rand(100,250)); $second = $value*360 + $first; imageFilledArc($i,250,150,250,250,$first,$second,$color, IMG_ARC_PIE); $first = $second; } */ imageTtfText($i, 30, 10, 200, 150, $red, 'georgia.ttf', 'PHP5 Взрыв!'); /* header("Content-type:image/gif"); imageGif($i); */ header("Content-type:image/jpg"); imageJpeg($i); //imageJpeg($i, "test.jpg"); //imageJpeg($i, "", 85);
<?php session_start(); $nChars = 5; $randStr = substr(md5(uniqid()), 0, $nChars); $_SESSION['captcha'] = $randStr; $im = imageCreateFromJpeg('images/noise.jpg'); imageAntiAlias($im, true); $x = 20; $y = 30; $delta_x = 40; for ($i = 0; $i < $nChars; $i++) { $size = mt_rand(18, 30); $angle = -30 + mt_rand(0, 60); $color = imageColorAllocate($im, 0, mt_rand(0, 255), mt_rand(0, 255)); imageTtfText($im, $size, $angle, $x, $y, $color, 'fonts/bellb.ttf', $randStr[$i]); $x += $delta_x; } header('Content-type: image/jpg'); imageJpeg($im, null, 50);
public function render() { ob_start(); if (!is_null($this->_background)) { $gdHandler = imageCreateFromPng($this->_background); } else { $gdHandler = imageCreateTrueColor(); } foreach ($this->_texts as $text) { $color = imageColorAllocate($gdHandler, $text['color'][self::COLOR_RED], $text['color'][self::COLOR_GREEN], $text['color'][self::COLOR_BLUE]); switch ($text['sizes']['alignment'] & 0xf) { case self::POSITION_CENTER: $text['sizes']['abscix'] -= floor(imageSX($gdHandler) / 2); break; case self::POSITION_RIGHT: $text['sizes']['abscix'] = imageSX($gdHandler) - ($text['sizes']['abscix'] + $text['sizes']['width']) - 10; break; case self::POSITION_LEFT: default: break; } $imageText = imageTtfText($gdHandler, $text['font_size'], $text['sizes']['angle'], $text['sizes']['abscix'], $text['sizes']['ordinate'], $color, $text['font_file'], $text['content']); } imagePng($gdHandler); imageDestroy($gdHandler); $imageData = ob_get_contents(); ob_end_clean(); return $imageData; }
/** * Render text depending of font type and available font extensions * * @param resource $image Image resource * @param string $text Text * @param int $type Font type * @param string $path Font path * @param ezcGraphColor $color Font color * @param ezcGraphCoordinate $position Position * @param float $size Textsize * @param ezcGraphRotation $rotation * * @return void */ protected function renderText($image, $text, $type, $path, ezcGraphColor $color, ezcGraphCoordinate $position, $size, ezcGraphRotation $rotation = null) { if ($rotation !== null) { // Rotation is relative to top left point of text and not relative // to the bounding coordinate system $rotation = new ezcGraphRotation($rotation->getRotation(), new ezcGraphCoordinate($rotation->getCenter()->x - $position->x, $rotation->getCenter()->y - $position->y)); } switch ($type) { case ezcGraph::PS_FONT: imagePsText($image, $text, $this->psFontRessources[$path], $size, $this->allocate($color), 1, $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), 0, 0, $rotation === null ? 0 : -$rotation->getRotation(), 4); break; case ezcGraph::TTF_FONT: switch (true) { case ezcBaseFeatures::hasFunction('imagefttext') && !$this->options->forceNativeTTF: imageFtText($image, $size, $rotation === null ? 0 : -$rotation->getRotation(), $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), $this->allocate($color), $path, $text); break; case ezcBaseFeatures::hasFunction('imagettftext'): imageTtfText($image, $size, $rotation === null ? 0 : -$rotation->getRotation(), $position->x + ($rotation === null ? 0 : $rotation->get(0, 2)), $position->y + ($rotation === null ? 0 : $rotation->get(1, 2)), $this->allocate($color), $path, $text); break; } break; } }
$randW = mt_rand(0, imageSX($im)); $randH = mt_rand(0, imageSY($im)); imageSetPixel($im, $randW, $randH, $color); } imageSetThickness($im, 2); $color = imageColorAllocate($im, 100, 100, 100); imageLine($im, 10, 30, 130, 20, $color); $color = imageColorAllocate($im, 70, 70, 70); $n1 = mt_rand(0, 9); imageTtfText($im, 25, 10, mt_rand(2, 10), mt_rand(25, 45), $color, "times.ttf", $n1); $color = imageColorAllocate($im, 255, 0, 50); $str = "ABCDIFGHIJKLMNOPKASTUVWXYZ"; $nw = mt_rand(0, 15); $n2 = $str[$nw]; imageTtftext($im, 22, -10, mt_rand(25, 35), mt_rand(25, 45), $color, "times.ttf", $n2); $color = imageColorAllocate($im, 50, 50, 50); $n3 = mt_rand(0, 9); imageTtfText($im, 25, 15, mt_rand(60, 70), mt_rand(25, 45), $color, "times.ttf", $n3); $color = imageColorAllocate($im, 250, 250, 250); $nw2 = mt_rand(15, 25); $n4 = $str[$nw2]; imageTtfText($im, 22, 30, mt_rand(90, 100), mt_rand(25, 45), $color, "times.ttf", $n4); $color = imageColorAllocate($im, 255, 220, 70); $n5 = mt_rand(0, 9); imageTtfText($im, 25, -20, mt_rand(115, 125), mt_rand(25, 45), $color, "times.ttf", $n5); $n = $n1 . $n2 . $n3 . $n4 . $n5; session_start(); $_SESSION['kap'] = md5(strtolower($n)); header("Content-type: image/jpeg"); imageJpeg($im); imageDestroy($im);
<?php session_start(); $nChars = rand(4, 6); $_SESSION["randStr"] = substr(md5(uniqid()), 0, $nChars); $im = imageCreateFromJpeg("images/noise.jpg"); imageAntiAlias($im, true); $x = rand(10, 30); $y = rand(15, 35); $deltaX = rand(30, 40); for ($i = 0; $i <= $nChars; $i++) { $size = rand(18, 30); $angle = -30 + rand(0, 60); $color = imageColorAllocate($im, rand(50, 150), rand(50, 150), rand(50, 150)); imageTtfText($im, $size, $angle, $x, $y, $color, 'fonts/georgia.ttf', $_SESSION["randStr"][$i]); $x = $x + $deltaX; } header("Content-type:image/jpg"); imageJpeg($im, null, 50);