protected static function _createTTFImage($txt) { if (!self::getInstance()) { return NULL; } /* else */ $bounds = ImageTTFBBox(self::$_font["size"], 0, self::$_font["family"], "W"); $fontHeight = abs($bounds[7] - $bounds[1]); $bounds = ImageTTFBBox(self::$_font["size"], 0, self::$_font["family"], $txt); $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offsetY = $fontHeight; $offsetX = 0; $image = imagecreate($width + self::$_padding * 2 + 1, $height + self::$_padding * 2 + 1); $background = ImageColorAllocate($image, self::$_backgroundColor["color"]["red"], self::$_backgroundColor["color"]["green"], self::$_backgroundColor["color"]["blue"]); $foreground = ImageColorAllocate($image, self::$_font["color"]["red"], self::$_font["color"]["green"], self::$_font["color"]["blue"]); if (self::$_transparent) { ImageColorTransparent($image, $background); } ImageInterlace($image, false); // render the image ImageTTFText($image, self::$_font["size"], 0, $offsetX + self::$_padding, $offsetY + self::$_padding, $foreground, self::$_font["family"], $txt); // print_r( self::$_font ); return $image; }
function JPGText($str, $fontname, $fontsize, $backcol, $txtcol) { global $layout; Header("Last-Modified: " . gmDate("D, d M Y H:i:s", Time()) . " GMT"); Header("Expires: " . gmDate("D, d M Y H:i:s", Time() - 3601) . " GMT"); Header("Pragma: no-cache"); Header("Cache-control: no-cache"); Header("Content-Type: image/jpeg"); $a = ImageTTFBBox($fontsize, 0, $fontname, $str); $width = $a[2] + 4; $bla = get_maximum_height($fontname, $fontsize); $height = $bla[0] + 3; $bl = $bla[1]; $im = ImageCreate($width, $height); $bgcol = ImageColorAllocate($im, $backcol['red'], $backcol['green'], $backcol['blue']); $fgcol = ImageColorAllocate($im, $txtcol['red'], $txtcol['green'], $txtcol['blue']); if (!function_exists(imagegif)) { imageTTFText($im, $fontsize, 0, 2, $bl + $fontsize / 6 + 2, $fgcol, $fontname, $str); imagejpeg($im, "", 80); } else { ImageColorTransparent($im, $bgcol); imageTTFText($im, $fontsize, 0, 2, $bl + $fontsize / 6 + 2, $fgcol, $fontname, $str); imagegif($im); } ImageDestroy($im); }
function TextToImage($text, $separate_line_after_chars = 40, $size = 24, $rotate = 0, $padding = 2, $transparent = true, $color = array('red' => 0, 'grn' => 0, 'blu' => 0), $bg_color = array('red' => 255, 'grn' => 255, 'blu' => 255)) { $amount_of_lines = ceil(strlen($text) / $separate_line_after_chars); $x = explode("\n", $text); $final = ''; foreach ($x as $key => $value) { $returnes = ''; do { $first_part = mb_substr($value, 0, $separate_line_after_chars, 'utf-8'); $value = "\n" . mb_substr($value, $separate_line_after_chars, null, 'utf-8'); $returnes .= $first_part; } while (mb_strlen($value, 'utf-8') > $separate_line_after_chars); $final .= $returnes . "\n"; } $text = $final; $width = $height = $offset_x = $offset_y = 0; $font = $_SERVER['DOCUMENT_ROOT'] . '/assets/css/journal.ttf'; // get the font height. $bounds = ImageTTFBBox($size, $rotate, $font, "W"); if ($rotate < 0) { $font_height = abs($bounds[7] - $bounds[1]); } elseif ($rotate > 0) { $font_height = abs($bounds[1] - $bounds[7]); } else { $font_height = abs($bounds[7] - $bounds[1]); } // determine bounding box. $bounds = ImageTTFBBox($size, $rotate, $font, $text); if ($rotate < 0) { $width = abs($bounds[4] - $bounds[0]); $height = abs($bounds[3] - $bounds[7]); $offset_y = $font_height; $offset_x = 0; } elseif ($rotate > 0) { $width = abs($bounds[2] - $bounds[6]); $height = abs($bounds[1] - $bounds[5]); $offset_y = abs($bounds[7] - $bounds[5]) + $font_height; $offset_x = abs($bounds[0] - $bounds[6]); } else { $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offset_y = $font_height; $offset_x = 0; } $image = imagecreate($width + $padding * 2 + 1, $height + $padding * 2 + 1); $background = ImageColorAllocate($image, $bg_color['red'], $bg_color['grn'], $bg_color['blu']); $foreground = ImageColorAllocate($image, $color['red'], $color['grn'], $color['blu']); if ($transparent) { ImageColorTransparent($image, $background); } ImageInterlace($image, true); // render the image ImageTTFText($image, $size, $rotate, $offset_x + $padding, $offset_y + $padding, $foreground, $font, $text); imagealphablending($image, true); imagesavealpha($image, true); // output PNG object. imagePNG($image, 'signature.png'); imagedestroy($image); }
function draw() { $width = 0; $height = 0; $offset_x = 0; $offset_y = 0; $bounds = array(); $image = ""; // get the font height. $bounds = ImageTTFBBox($this->size, $this->rot, $this->font, "W"); if ($this->rot < 0) { $font_height = abs($bounds[7] - $bounds[1]); } else { if ($this->rot > 0) { $font_height = abs($bounds[1] - $bounds[7]); } else { $font_height = abs($bounds[7] - $bounds[1]); } } // determine bounding box. $bounds = ImageTTFBBox($this->size, $this->rot, $this->font, $this->msg); if ($this->rot < 0) { $width = abs($bounds[4] - $bounds[0]); $height = abs($bounds[3] - $bounds[7]); $offset_y = $font_height; $offset_x = 0; } else { if ($this->rot > 0) { $width = abs($bounds[2] - $bounds[6]); $height = abs($bounds[1] - $bounds[5]); $offset_y = abs($bounds[7] - $bounds[5]) + $font_height; $offset_x = abs($bounds[0] - $bounds[6]); } else { $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offset_y = $font_height; $offset_x = 0; } } $image = imagecreate($width + $this->padX * 2 + 1, $height + $this->padY * 2 + 1); $background = ImageColorAllocate($image, $this->bg_red, $this->bg_grn, $this->bg_blu); $foreground = ImageColorAllocate($image, $this->red, $this->grn, $this->blu); if ($this->transparent) { ImageColorTransparent($image, $background); } ImageInterlace($image, false); // render the image ImageTTFText($image, $this->size, $this->rot, $offset_x + $this->padX, $offset_y + $this->padY, $foreground, $this->font, $this->msg); // output PNG object. imagePNG($image); }
function pc_ImageTTFCenter($image, $text, $font, $size) { // find the size of the image $xi = ImageSX($image); $yi = ImageSY($image); // find the size of the text $box = ImageTTFBBox($size, 0, $font, $text); $xr = abs(max($box[2], $box[4])); $yr = abs(max($box[5], $box[7])); // compute centering $x = intval(($xi - $xr) / 2); $y = intval(($yi + $yr) / 2); return array($x, $y); }
public function draw() { $font = $this->_getFont(); $htexte = 'dg' . $this->getText(); $hdim = ImageTTFBBox($this->getSize(), 0, $font, $htexte); $wdim = ImageTTFBBox($this->getSize(), 0, $font, $this->getText()); $dx = max($wdim[2], $wdim[4]) - min($wdim[0], $wdim[6]) + ceil($this->getSize() / 8); $dy = max($hdim[1], $hdim[3]) - min($hdim[5], $hdim[7]) + ceil($this->getSize() / 8); $img = ImageCreate(max($dx, 1), max($dy, 1)); $noir = ImageColorAllocate($img, 0, 0, 0); $blanc = ImageColorAllocate($img, 255, 255, 255); $blanc = imagecolortransparent($img, $blanc); ImageFilledRectangle($img, 0, 0, $dx, $dy, $blanc); ImageTTFText($img, $this->getSize(), $angle, 0, -min($hdim[5], $hdim[7]), $noir, $font, $this->getText()); return $img; }
function rw_cryptx_init_tinyurl() { global $cryptX_var; $url = $_SERVER['REQUEST_URI']; $params = explode('/', $url); if (count($params) > 1) { $tiny_url = $params[count($params) - 2]; if ($tiny_url == md5(get_bloginfo('url'))) { $font = $cryptX_var['c2i_font']; $msg = $params[count($params) - 1]; $size = $cryptX_var['c2i_fontSize']; $pad = 1; $transparent = 1; $red = hexdec(substr($cryptX_var['c2i_fontRGB'], 0, 2)); $grn = hexdec(substr($cryptX_var['c2i_fontRGB'], 2, 2)); $blu = hexdec(substr($cryptX_var['c2i_fontRGB'], 4, 2)); $bg_red = 255 - $red; $bg_grn = 255 - $grn; $bg_blu = 255 - $blu; $width = 0; $height = 0; $offset_x = 0; $offset_y = 0; $bounds = array(); $image = ""; $bounds = ImageTTFBBox($size, 0, $font, "W"); $font_height = abs($bounds[7] - $bounds[1]); $bounds = ImageTTFBBox($size, 0, $font, $msg); $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offset_y = $font_height + abs(($height - $font_height) / 2) - 1; $offset_x = 0; $image = imagecreatetruecolor($width + $pad * 2, $height + $pad * 2); imagesavealpha($image, true); $foreground = ImageColorAllocate($image, $red, $grn, $blu); $background = imagecolorallocatealpha($image, 0, 0, 0, 127); imagefill($image, 0, 0, $background); ImageTTFText($image, $size, 0, $offset_x + $pad, $offset_y + $pad, $foreground, $font, $msg); Header("Content-type: image/png"); imagePNG($image); die; } } }
function process() { global $CONFIG; $matches = array(); if (!preg_match("/^([0-9a-zA-Z]+)\\.png\$/", $this->file, $matches)) { error_exit("Invalid image request for {$this->file}"); } $code = $matches[1]; $basepath = trim($CONFIG['paths']['base_url'], '/') . '/image/pins'; $basefile = trim($CONFIG['paths']['file_path'], '/') . '/image/pins'; $localfile = "{$basefile}/{$code}.png"; if (file_exists($localfile)) { header("Location: http://{$_SERVER['HTTP_HOST']}/{$basepath}/{$code}.png"); } else { if (!function_exists('ImageCreateFromPNG')) { header("Location: http://{$_SERVER['HTTP_HOST']}/{$basepath}/blank-marker.png"); } else { $font = 'ttf-bitstream-vera/Vera'; $size = 6; if (strlen($code) < 3) { # Bigger image for number-only pins $size = 8; } $im = ImageCreateFromPNG("{$basefile}/blank-marker.png"); imageSaveAlpha($im, true); $tsize = ImageTTFBBox($size, 0, $font, $code); $textbg = ImageColorAllocate($im, 255, 119, 207); $black = ImageColorAllocate($im, 0, 0, 0); $dx = abs($tsize[2] - $tsize[0]); $dy = abs($tsize[5] - $tsize[3]); $x = (ImageSx($im) - $dx) / 2 + 1; $y = (ImageSy($im) - $dy) / 2; ImageTTFText($im, $size, 0, $x, $y, $black, $font, $code); header('Content-Type: image/png'); ImagePNG($im); ImagePNG($im, $localfile); ImageDestroy($im); } } exit; }
/** * Get the height of a text. * * Note! This method can give some peculiar results, since ImageTTFBBox() returns the total * bounding box of a text, where ImageTTF() writes the text on the baseline of the text, that * is 'g', 'p', 'q' and other letters that dig under the baseline will appear to have a larger * height than they actually do. Have a look at the tests/text.php test case - the first two * columns, 'left and 'center', both look alright, whereas the last column, 'right', appear * with a larger space between the first text and the second. This is because the total height * is actually smaller by exactly the number of pixels that the 'g' digs under the baseline. * Remove the 'g' from the text and they appear correct. * * @param string $text The text to get the height of * @param bool $force Force the method to calculate the size * @return int The height of the text */ function textHeight($text, $force = false) { if (isset($this->_font['file'])) { $angle = 0; if (isset($this->_font['angle'])) { $angle = $this->_font['angle']; } $linebreaks = substr_count($text, "\n"); if ($angle == 0 && $force === false) { /* * if the angle is 0 simply return the size, due to different * heights for example for x-axis labels, making the labels * _not_ appear as written on the same baseline */ return $this->_font['size'] + ($this->_font['size'] + 2) * $linebreaks; } $height = 0; $lines = explode("\n", $text); foreach ($lines as $line) { $bounds = ImageTTFBBox($this->_font['size'], $angle, $this->_font['file'], $line); $y0 = min($bounds[1], $bounds[3], $bounds[5], $bounds[7]); $y1 = max($bounds[1], $bounds[3], $bounds[5], $bounds[7]); $height += abs($y0 - $y1); } return $height + $linebreaks * 2; } else { if (isset($this->_font['vertical']) && $this->_font['vertical']) { $width = 0; $lines = explode("\n", $text); foreach ($lines as $line) { $width = max($width, ImageFontWidth($this->_font['font']) * strlen($line)); } return $width; } else { return ImageFontHeight($this->_font['font']) * (substr_count($text, "\n") + 1); } } }
ImageTTFText($im, $title_size, 0, $title_x, $title_y, $text_color, $font, $title); // Draw a base line from a little above first bar location // to a little below last ImageLine($im, $x, $y - 5, $x, $height - 15, $line_color); /******************************************* Draw data into graph *******************************************/ // Get each line of db data and draw corresponding bars while ($row = mysql_fetch_object($result)) { if ($total_votes > 0) { $percent = intval(round($row->num_votes / $total_votes * 100)); } else { $percent = 0; } // display percent for this value $percent_dimensions = ImageTTFBBox($main_size, 0, $font, $percent . '%'); $percent_length = $percent_dimensions[2] - $percent_dimensions[0]; ImageTTFText($im, $main_size, 0, $width - $percent_length - $text_indent, $y + $bar_height / 2, $percent_color, $font, $percent . '%'); if ($total_votes > 0) { $right_value = intval(round($row->num_votes / $total_votes * 100)); } else { $right_value = 0; } // length of bar for this value $bar_length = $x + $right_value * $bar_unit; // draw bar for this value ImageFilledRectangle($im, $x, $y - 2, $bar_length, $y + $bar_height, $bar_color); // draw title for this value ImageTTFText($im, $main_size, 0, $text_indent, $y + $bar_height / 2, $text_color, $font, "{$row->candidate}"); // draw outline showing 100% ImageRectangle($im, $bar_length + 1, $y - 2, $x + 100 * $bar_unit, $y + $bar_height, $line_color);
function cforms2_reset_captcha() { check_admin_referer('cforms2_reset_captcha'); $cformsSettings = get_option('cforms_settings'); $cap = $cformsSettings['global']['cforms_captcha_def']; ### overwrite for admin demo purposes, no cookie set though if (count($_GET) > 4) { $cap = $_GET; } $min = cforms2_prepVal($cap['c1'], 4); $max = cforms2_prepVal($cap['c2'], 5); $src = cforms2_prepVal($cap['ac'], 'abcdefghijkmnpqrstuvwxyz23456789'); $img_sz_type = 0; $img_sz_width = cforms2_prepVal($cap['w'], 115); $img_sz_height = cforms2_prepVal($cap['h'], 25); $im_bg_type = 1; $im_bg_url = plugin_dir_path(__FILE__) . 'captchabg/' . cforms2_prepVal($cap['bg'], '1.gif'); $font_url = plugin_dir_path(__FILE__) . 'captchafonts/' . cforms2_prepVal($cap['f'], 'font4.ttf'); $min_font_size = cforms2_prepVal($cap['f1'], 17); $max_font_size = cforms2_prepVal($cap['f2'], 19); $min_angle = cforms2_prepVal($cap['a1'], -12); $max_angle = cforms2_prepVal($cap['a2'], 12); $col_txt_type = 4; $col = cforms2_prepVal($cap['c'], '#000066'); $col_txt_r = hexdec(substr($col, 1, 2)); $col_txt_g = hexdec(substr($col, 3, 2)); $col_txt_b = hexdec(substr($col, 5, 2)); $border = cforms2_prepVal($cap['l'], '#000066'); $border_r = hexdec(substr($border, 1, 2)); $border_g = hexdec(substr($border, 3, 2)); $border_b = hexdec(substr($border, 5, 2)); $char_padding = 2; $output_type = 'png'; $no = cforms2_prepVal($_GET['ts'], ''); ### captcha random code $srclen = strlen($src) - 1; $length = mt_rand($min, $max); $turing = ''; for ($i = 0; $i < $length; $i++) { $turing .= substr($src, mt_rand(0, $srclen), 1); } $tu = $cap['i'] == 'i' ? strtolower($turing) : $turing; if (!(isset($_GET['c1']) || isset($_GET['c2']) || isset($_GET['ac']))) { setcookie("turing_string_" . $no, $cap['i'] . '+' . md5($tu), time() + 60 * 60 * 5, "/"); } $font = $font_url; ### initialize variables $length = strlen($turing); $data = array(); $image_width = $image_height = 0; $codelen = 0; ### build the data array of the characters, size, placement, etc. for ($i = 0; $i < $length; $i++) { $char = substr($turing, $i, 1); $size = mt_rand($min_font_size, $max_font_size); $angle = mt_rand($min_angle, $max_angle); $bbox = ImageTTFBBox($size, $angle, $font, $char); $char_width = max($bbox[2], $bbox[4]) - min($bbox[0], $bbox[6]); $char_height = max($bbox[1], $bbox[3]) - min($bbox[7], $bbox[5]); $codelen = $codelen + $char_width + $char_padding; $image_width += $char_width + $char_padding; $image_height = max($image_height, $char_height); $data[] = array('char' => $char, 'size' => $size, 'angle' => $angle, 'height' => $char_height, 'width' => $char_width); } ### calculate the final image size, adding some padding $x_padding = 12; if ($img_sz_type == 1) { $image_width += $x_padding * 2; $image_height = $image_height * 1.5 + 2; } else { $image_width = $img_sz_width; $image_height = $img_sz_height; } ### build the image, and allocte the colors $im = ImageCreate($image_width, $image_height); $d1 = $d2 = $d3 = 0; while ($d1 < 50 and $d2 < 50 and $d3 < 50) { $r = mt_rand(200, 255); $g = mt_rand(200, 255); $b = mt_rand(200, 255); $d1 = abs($r - $g); $d2 = abs($r - $b); $d3 = abs($g - $b); } ImageColorAllocate($im, $r, $g, $b); $color_border = ImageColorAllocate($im, $border_r, $border_g, $border_b); ImageColorAllocate($im, round($r * 0.85), round($g * 0.85), round($b * 0.85)); ImageColorAllocate($im, round($r * 0.95), round($g * 0.95), round($b * 0.95)); ImageColorAllocate($im, round($r * 0.9), round($g * 0.9), round($b * 0.9)); $d1 = mt_rand(0, 50); $d2 = mt_rand(0, 50); $d3 = mt_rand(0, 50); $d1 = $d2 = $d3 = 0; while ($d1 < 100 and $d2 < 100 and $d3 < 100) { $r = mt_rand(0, 150); $g = mt_rand(0, 150); $b = mt_rand(0, 150); $d1 = abs($r - $g); $d2 = abs($r - $b); $d3 = abs($g - $b); } switch ($col_txt_type) { case 1: $col_txt = ImageColorAllocate($im, $r, $g, $b); break; case 2: $col_txt = ImageColorAllocate($im, 0, 0, 0); break; case 3: $col_txt = ImageColorAllocate($im, 255, 255, 255); break; case 4: $col_txt = ImageColorAllocate($im, $col_txt_r, $col_txt_g, $col_txt_b); break; } $image_data = getimagesize($im_bg_url); $image_type = $image_data[2]; if ($image_type == 1) { $img_src = imagecreatefromgif($im_bg_url); } elseif ($image_type == 2) { $img_src = imagecreatefromjpeg($im_bg_url); } elseif ($image_type == 3) { $img_src = imagecreatefrompng($im_bg_url); } if ($im_bg_type == 1) { imagesettile($im, $img_src); imageFilledRectangle($im, 0, 0, $image_width, $image_height, IMG_COLOR_TILED); } else { imagecopyresampled($im, $img_src, 0, 0, 0, 0, $image_width, $image_height, $image_data[0], $image_data[1]); } $pos_x = ($image_width - $codelen) / 2; foreach ($data as $d) { $pos_y = ($image_height + $d['height']) / 2; ImageTTFText($im, $d['size'], $d['angle'], $pos_x, $pos_y, $col_txt, $font, $d['char']); $pos_x += $d['width'] + $char_padding; } ### a nice border ImageRectangle($im, 0, 0, $image_width - 1, $image_height - 1, $color_border); // There can be some output from other loaded PHP files, therefore clean output. ob_end_clean(); switch ($output_type) { case 'jpeg': Header('Content-type: image/jpeg'); ImageJPEG($im, NULL, 100); break; case 'png': default: Header('Content-type: image/png'); ImagePNG($im); break; } flush(); ImageDestroy($im); die; }
/** * Wrapper for ImageTTFText * * @param resource $im (See argument for PHP function imageTTFtext()) * @param int $fontSize (See argument for PHP function imageTTFtext()) * @param int $angle (See argument for PHP function imageTTFtext()) * @param int $x (See argument for PHP function imageTTFtext()) * @param int $y (See argument for PHP function imageTTFtext()) * @param int $color (See argument for PHP function imageTTFtext()) * @param string $fontFile (See argument for PHP function imageTTFtext()) * @param string $string (See argument for PHP function imageTTFtext()). UTF-8 string, possibly with entities in. * @param array $splitRendering Split-rendering configuration * @param int $sF Scale factor * @return void */ public function ImageTTFTextWrapper($im, $fontSize, $angle, $x, $y, $color, $fontFile, $string, $splitRendering, $sF = 1) { // Initialize: $stringParts = $this->splitString($string, $splitRendering, $fontSize, $fontFile); $x = ceil($sF * $x); $y = ceil($sF * $y); // Traverse string parts: foreach ($stringParts as $i => $strCfg) { // Initialize: $colorIndex = $color; // Set custom color if any (only when niceText is off): if ($strCfg['color'] && $sF == 1) { $cols = $this->convertColor($strCfg['color']); $colorIndex = ImageColorAllocate($im, $cols[0], $cols[1], $cols[2]); $colorIndex = $color >= 0 ? $colorIndex : -$colorIndex; } // Setting xSpaceBefore if ($i) { $x += (int) $strCfg['xSpaceBefore']; $y -= (int) $strCfg['ySpaceBefore']; } $fontFile = self::prependAbsolutePath($strCfg['fontFile']); if (is_readable($fontFile)) { // Render part: ImageTTFText($im, GeneralUtility::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, $x, $y, $colorIndex, $fontFile, $strCfg['str']); // Calculate offset to apply: $wordInf = ImageTTFBBox(GeneralUtility::freetypeDpiComp($sF * $strCfg['fontSize']), $angle, self::prependAbsolutePath($strCfg['fontFile']), $strCfg['str']); $x += $wordInf[2] - $wordInf[0] + (int) $splitRendering['compX'] + (int) $strCfg['xSpaceAfter']; $y += $wordInf[5] - $wordInf[7] - (int) $splitRendering['compY'] - (int) $strCfg['ySpaceAfter']; } else { debug('cannot read file: ' . $fontFile, GraphicalFunctions::class . '::ImageTTFTextWrapper()'); } } }
/** * @param string * @param integer * @return string * @access private */ function _createImage($word, $baseline) { $font = isset($this->_gtextAttributes['font']) ? $this->_gtextAttributes['font'] : 'arial.ttf'; $fh = isset($this->_gtextAttributes['fontsize']) ? $this->_gtextAttributes['fontsize'] : 12; $bgcolor = isset($this->_gtextAttributes['bgcolor']) ? $this->_gtextAttributes['bgcolor'] : '#ffffff'; $fgcolor = isset($this->_gtextAttributes['fgcolor']) ? $this->_gtextAttributes['fgcolor'] : '#ffffff'; $antialias = isset($this->_gtextAttributes['antialias']) ? $this->_gtextAttributes['antialias'] : 'yes'; $transparency = isset($this->_gtextAttributes['transparency']) ? $this->_gtextAttributes['transparency'] : 'yes'; $cacheable = isset($this->_gtextAttributes['cacheable']) ? $this->_gtextAttributes['cacheable'] : 'yes'; $spacing = isset($this->_gtextAttributes['spacing']) ? $this->_gtextAttributes['spacing'] : 2; $border = isset($this->_gtextAttributes['border']) ? $this->_gtextAttributes['border'] : 0; $bordercolor = isset($this->_gtextAttributes['bordercolor']) ? $this->_gtextAttributes['bordercolor'] : '#ff0000'; /* The cache name is derived from all attributes and cdata. * This is very conserative and may create to many cachefiles, * but better to err on the safe side. */ $cachefile = md5(XML_Util::attributesToString($this->_gtextAttributes) . ':' . $word) . '.png'; $cacheDir = $_SERVER['DOCUMENT_ROOT'] . PEAR_XML_TRANSFORMER_IMAGE_cacheDir; $cacheName = "{$cacheDir}/{$cachefile}"; $cacheURL = PEAR_XML_TRANSFORMER_IMAGE_cacheDir . "/{$cachefile}"; if (!is_dir($cacheDir)) { mkdir($cacheDir, 01777); } /* Don't do the same work twice. */ if (file_exists($cacheName) && $cacheable != 'no') { return $cacheURL; } $r = ImageTTFBBox($fh, 0, $font, $word); $w = max(1 / 10 * $fh, abs($r[2] - $r[0])); $h = max(1, abs($r[7] - $r[1])); $x = $r[0]; $y = $baseline; $www = $w + 2 * ($spacing + $border); $hhh = $fh + 2 * ($spacing + $border); $im = ImageCreate($www, $hhh); list($r, $g, $b) = $this->_colorString($bgcolor); $bg = ImageColorAllocate($im, $r, $g, $b); if ($transparency != 'no') { ImageColorTransparent($im, $bg); } list($r, $g, $b) = $this->_colorString($fgcolor); $fg = ImageColorAllocate($im, $r, $g, $b); if ($antialias == 'no') { $fg = -$fg; } list($r, $g, $b) = $this->_colorString($bordercolor); $bo = ImageColorAllocate($im, $r, $g, $b); ImageFilledRectangle($im, 0, 0, $www, $hhh, $bg); if ($border > 0) { for ($i = $border; $i >= 0; $i--) { $x1 = $y1 = $i; $x2 = $www - $i - 1; $y2 = $hhh - $i - 1; ImageRectangle($im, $x1, $y1, $x2, $y2, $bo); } } ImageTTFText($im, $fh, 0, -$x + $spacing + $border, $hhh - (2 + $y + $spacing + $border), $fg, $font, $word); ImagePNG($im, $cacheName); ImageDestroy($im); return $cacheURL; }
function bwg_imagettfbboxdimensions($font_size, $font_angle, $font, $text) { $box = @ImageTTFBBox($font_size, $font_angle, $font, $text) or die; $max_x = max(array($box[0], $box[2], $box[4], $box[6])); $max_y = max(array($box[1], $box[3], $box[5], $box[7])); $min_x = min(array($box[0], $box[2], $box[4], $box[6])); $min_y = min(array($box[1], $box[3], $box[5], $box[7])); return array("width" => $max_x - $min_x, "height" => $max_y - $min_y); }
function _StrokeTTF($x, $y, $txt, $dir = 0, $paragraph_align = "left", $debug = false) { // Setupo default inter line margin for paragraphs to // 25% of the font height. $ConstLineSpacing = 0.25; // Remember the anchor point before adjustment if ($debug) { $ox = $x; $oy = $y; } if (!ereg("\n", $txt) || $dir > 0 && ereg("\n", $txt)) { // Format a single line $txt = $this->AddTxtCR($txt); $bbox = $this->GetBBoxTTF($txt, $dir); // Align x,y ot lower left corner of bbox $x -= $bbox[0]; $y -= $bbox[1]; // Note to self: "topanchor" is deprecated after we changed the // bopunding box stuff. if ($this->text_halign == "right" || $this->text_halign == "topanchor") { $x -= $bbox[2] - $bbox[0]; } elseif ($this->text_halign == "center") { $x -= ($bbox[2] - $bbox[0]) / 2; } if ($this->text_valign == "top") { $y += abs($bbox[5]) + $bbox[1]; } elseif ($this->text_valign == "center") { $y -= ($bbox[5] - $bbox[1]) / 2; } ImageTTFText($this->img, $this->font_size, $dir, $x, $y, $this->current_color, $this->font_file, $txt); if ($debug) { // Draw the bounding rectangle and the bounding box $box = @ImageTTFBBox($this->font_size, $dir, $this->font_file, $txt); $p = array(); $p1 = array(); for ($i = 0; $i < 4; ++$i) { $p[] = $bbox[$i * 2] + $x; $p[] = $bbox[$i * 2 + 1] + $y; $p1[] = $box[$i * 2] + $x; $p1[] = $box[$i * 2 + 1] + $y; } // Draw bounding box $this->PushColor('green'); $this->Polygon($p1, true); $this->PopColor(); // Draw bounding rectangle $this->PushColor('darkgreen'); $this->Polygon($p, true); $this->PopColor(); // Draw a cross at the anchor point $this->PushColor('red'); $this->Line($ox - 15, $oy, $ox + 15, $oy); $this->Line($ox, $oy - 15, $ox, $oy + 15); $this->PopColor(); } } else { // Format a text paragraph $fh = $this->GetFontHeight(); // Line margin is 25% of font height $linemargin = round($fh * $ConstLineSpacing); $fh += $linemargin; $w = $this->GetTextWidth($txt); $y -= $linemargin / 2; $tmp = split("\n", $txt); $nl = count($tmp); $h = $nl * $fh; if ($this->text_halign == "right") { $x -= $dir == 0 ? $w : $h; } elseif ($this->text_halign == "center") { $x -= $dir == 0 ? $w / 2 : $h / 2; } if ($this->text_valign == "top") { $y += $dir == 0 ? $h : $w; } elseif ($this->text_valign == "center") { $y += $dir == 0 ? $h / 2 : $w / 2; } // Here comes a tricky bit. // Since we have to give the position for the string at the // baseline this means thaht text will move slightly up // and down depending on any of it's character descend below // the baseline, for example a 'g'. To adjust the Y-position // we therefore adjust the text with the baseline Y-offset // as used for the current font and size. This will keep the // baseline at a fixed positoned disregarding the actual // characters in the string. $standardbox = $this->GetTTFBBox('Gg', $dir); $yadj = $standardbox[1]; $xadj = $standardbox[0]; for ($i = 0; $i < $nl; ++$i) { $wl = $this->GetTextWidth($tmp[$i]); $bbox = $this->GetTTFBBox($tmp[$i], $dir); if ($paragraph_align == "left") { $xl = $x; } elseif ($paragraph_align == "right") { $xl = $x + ($w - $wl); } else { // Center $xl = $x + $w / 2 - $wl / 2; } $xl -= $bbox[0]; $yl = $y - $yadj; $xl = $xl - $xadj; ImageTTFText($this->img, $this->font_size, $dir, $xl, $yl - ($h - $fh) + $fh * $i, $this->current_color, $this->font_file, $tmp[$i]); if ($debug) { // Draw the bounding rectangle around each line $box = @ImageTTFBBox($this->font_size, $dir, $this->font_file, $tmp[$i]); $p = array(); for ($j = 0; $j < 4; ++$j) { $p[] = $bbox[$j * 2] + $xl; $p[] = $bbox[$j * 2 + 1] + $yl - ($h - $fh) + $fh * $i; } // Draw bounding rectangle $this->PushColor('darkgreen'); $this->Polygon($p, true); $this->PopColor(); } } if ($debug) { // Draw a cross at the anchor point $this->PushColor('red'); $this->Line($ox - 25, $oy, $ox + 25, $oy); $this->Line($ox, $oy - 25, $ox, $oy + 25); $this->PopColor(); } } }
/** * Based on the Watermark function by Marek Malcherek * http://www.malcherek.de * * @param string $color * @param string $wmFont * @param int $wmSize * @param int $wmOpaque */ function watermarkCreateText($color = '000000', $wmFont, $wmSize = 10, $wmOpaque = 90) { // set font path $wmFontPath = NGGALLERY_ABSPATH . "fonts/" . $wmFont; if (!is_readable($wmFontPath)) { return; } // This function requires both the GD library and the FreeType library. if (!function_exists('ImageTTFBBox')) { return; } $TextSize = @ImageTTFBBox($wmSize, 0, $wmFontPath, $this->watermarkText) or die; $TextWidth = abs($TextSize[2]) + abs($TextSize[0]); $TextHeight = abs($TextSize[7]) + abs($TextSize[1]); // Create Image for Text $this->workingImage = ImageCreateTrueColor($TextWidth, $TextHeight); ImageSaveAlpha($this->workingImage, true); ImageAlphaBlending($this->workingImage, false); $bgText = imagecolorallocatealpha($this->workingImage, 255, 255, 255, 127); imagefill($this->workingImage, 0, 0, $bgText); $wmTransp = 127 - $wmOpaque * 1.27; $rgb = $this->hex2rgb($color, false); $TextColor = imagecolorallocatealpha($this->workingImage, $rgb[0], $rgb[1], $rgb[2], $wmTransp); // Create Text on image imagettftext($this->workingImage, $wmSize, 0, 0, abs($TextSize[5]), $TextColor, $wmFontPath, $this->watermarkText); $this->watermarkImgPath = $this->workingImage; return; }
function get_boundaryBox($message) { $points = $message['points']; $angle = $message['angle']; $font = $this->parameter['path_to_fonts'] . $message['font']; $text = $message['text']; //print ('get_boundaryBox'); //expandPre($message); // get font size $bounds = ImageTTFBBox($points, $angle, $font, "W"); if ($angle < 0) { $fontHeight = abs($bounds[7] - $bounds[1]); } else { if ($angle > 0) { $fontHeight = abs($bounds[1] - $bounds[7]); } else { $fontHeight = abs($bounds[7] - $bounds[1]); } } // get boundary box and offsets for printing at an angle $bounds = ImageTTFBBox($points, $angle, $font, $text); if ($angle < 0) { $width = abs($bounds[4] - $bounds[0]); $height = abs($bounds[3] - $bounds[7]); $offsetY = abs($bounds[3] - $bounds[1]); $offsetX = 0; } else { if ($angle > 0) { $width = abs($bounds[2] - $bounds[6]); $height = abs($bounds[1] - $bounds[5]); $offsetY = 0; $offsetX = abs($bounds[0] - $bounds[6]); } else { $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offsetY = 0; $offsetX = 0; } } //return values return array('width' => $width, 'height' => $height, 'offsetX' => $offsetX, 'offsetY' => $offsetY); }
function ProcessTextTTF($draw_it, $font, $angle, $x, $y, $color, $text, $h_factor, $v_factor) { # Extract font parameters (see SetFontTTF): $font_file = $font['font']; $font_size = $font['size']; $font_height = $font['height']; $line_spacing = $this->GetLineSpacing($font); # Break up the text into lines, trim whitespace. # Calculate the total width and height of the text box at 0 degrees. # Save the trimmed lines and their widths for later when drawing. # To get uniform spacing, don't use the actual line heights. # Total height = Font-specific line heights plus inter-line spacing. # Total width = width of widest line. # Last Line Descent is the offset from the bottom to the text baseline. # Note: For some reason, ImageTTFBBox uses (-1,-1) as the reference point. # So 1+bbox[1] is the baseline to bottom distance. $total_width = 0; $lastline_descent = 0; foreach (explode("\n", $text) as $each_line) { $lines[] = $line = trim($each_line); $bbox = ImageTTFBBox($font_size, 0, $font_file, $line); $line_widths[] = $width = $bbox[2] - $bbox[0]; if ($width > $total_width) { $total_width = $width; } $lastline_descent = 1 + $bbox[1]; } $n_lines = count($lines); $total_height = $n_lines * $font_height + ($n_lines - 1) * $line_spacing; # Calculate the rotation matrix for the text's angle. Remember that GD points Y down, # so the sin() terms change sign. $theta = deg2rad($angle); $cos_t = cos($theta); $sin_t = sin($theta); $r00 = $cos_t; $r01 = $sin_t; $r10 = -$sin_t; $r11 = $cos_t; # Make a bounding box of the right size, with upper left corner at (0,0). # By convention, the point order is: LL, LR, UR, UL. # Note this is still working with the text at 0 degrees. # When sizing text (SizeText), use the overall size with descenders. # This tells the caller how much room to leave for the text. # When drawing text (DrawText), use the size without descenders - that # is, down to the baseline. This is for accurate positioning. $b[0] = 0; if ($draw_it) { $b[1] = $total_height; } else { $b[1] = $total_height + $lastline_descent; } $b[2] = $total_width; $b[3] = $b[1]; $b[4] = $total_width; $b[5] = 0; $b[6] = 0; $b[7] = 0; # Rotate the bounding box, then offset to the reference point: for ($i = 0; $i < 8; $i += 2) { $x_b = $b[$i]; $y_b = $b[$i + 1]; $c[$i] = $x + $r00 * $x_b + $r01 * $y_b; $c[$i + 1] = $y + $r10 * $x_b + $r11 * $y_b; } # Get an orthogonal (aligned with X and Y axes) bounding box around it, by # finding the min and max X and Y: $bbox_ref_x = $bbox_max_x = $c[0]; $bbox_ref_y = $bbox_max_y = $c[1]; for ($i = 2; $i < 8; $i += 2) { $x_b = $c[$i]; if ($x_b < $bbox_ref_x) { $bbox_ref_x = $x_b; } elseif ($bbox_max_x < $x_b) { $bbox_max_x = $x_b; } $y_b = $c[$i + 1]; if ($y_b < $bbox_ref_y) { $bbox_ref_y = $y_b; } elseif ($bbox_max_y < $y_b) { $bbox_max_y = $y_b; } } $bbox_width = $bbox_max_x - $bbox_ref_x; $bbox_height = $bbox_max_y - $bbox_ref_y; if (!$draw_it) { # Return the bounding box, rounded up (so it always contains the text): return array((int) ceil($bbox_width), (int) ceil($bbox_height)); } $interline_step = $font_height + $line_spacing; // Line-to-line step # Calculate the offsets from the supplied reference point to the # upper-left corner of the text. # Start at the reference point at the upper left corner of the bounding # box (bbox_ref_x, bbox_ref_y) then adjust it for the 9 point alignment. # h,v_factor are 0,0 for top,left, .5,.5 for center,center, 1,1 for bottom,right. # $off_x = $bbox_ref_x + $bbox_width * $h_factor - $x; # $off_y = $bbox_ref_y + $bbox_height * $v_factor - $y; # Then use that offset to calculate back to the supplied reference point x, y # to get the text base point. # $qx = $x - $off_x; # $qy = $y - $off_y; # Reduces to: $qx = 2 * $x - $bbox_ref_x - $bbox_width * $h_factor; $qy = 2 * $y - $bbox_ref_y - $bbox_height * $v_factor; # Check for debug callback. Don't calculate bounding box unless it is wanted. if ($this->GetCallback('debug_textbox')) { # Calculate the orthogonal bounding box coordinates for debug testing. # qx, qy is upper left corner relative to the text. # Calculate px,py: upper left corner (absolute) of the bounding box. # There are 4 equation sets for this, depending on the quadrant: if ($sin_t > 0) { if ($cos_t > 0) { # Quadrant: 0d - 90d: $px = $qx; $py = $qy - $total_width * $sin_t; } else { # Quadrant: 90d - 180d: $px = $qx + $total_width * $cos_t; $py = $qy - $bbox_height; } } else { if ($cos_t < 0) { # Quadrant: 180d - 270d: $px = $qx - $bbox_width; $py = $qy + $total_height * $cos_t; } else { # Quadrant: 270d - 360d: $px = $qx + $total_height * $sin_t; $py = $qy; } } $this->DoCallback('debug_textbox', $px, $py, $bbox_width, $bbox_height); } # Since alignment is applied after rotation, which parameter is used # to control alignment of each line within the text box varies with # the angle. # Angle (degrees): Line alignment controlled by: # -45 < angle <= 45 h_align # 45 < angle <= 135 reversed v_align # 135 < angle <= 225 reversed h_align # 225 < angle <= 315 v_align if ($cos_t >= $sin_t) { if ($cos_t >= -$sin_t) { $line_align_factor = $h_factor; } else { $line_align_factor = $v_factor; } } else { if ($cos_t >= -$sin_t) { $line_align_factor = 1 - $v_factor; } else { $line_align_factor = 1 - $h_factor; } } # Now we have the start point, spacing and in-line alignment factor. # We are finally ready to start drawing the text, line by line. for ($i = 0; $i < $n_lines; $i++) { # For drawing TTF text, the reference point is the left edge of the # text baseline (not the lower left corner of the bounding box). # The following also adjusts for horizontal (relative to # the text) alignment of the current line within the box. # What is happening is rotation of this vector by the text angle: # (x = (total_width - line_width) * factor, y = font_height) $width_factor = ($total_width - $line_widths[$i]) * $line_align_factor; $rx = $qx + $r00 * $width_factor + $r01 * $font_height; $ry = $qy + $r10 * $width_factor + $r11 * $font_height; # Finally, draw the text: ImageTTFText($this->img, $font_size, $angle, $rx, $ry, $color, $font_file, $lines[$i]); # Step to position of next line. # This is a rotation of (x=0,y=height+line_spacing) by $angle: $qx += $r01 * $interline_step; $qy += $r11 * $interline_step; } return True; }
function TTFBBoxSize($size, $angle, $font, $string) { // First, assume angle < 90 $arr = ImageTTFBBox($size, 0, $font, $string); $flat_width = $arr[2] - $arr[0]; $flat_height = abs($arr[3] - $arr[5]); // Now the bounding box $angle = deg2rad($angle); $width = ceil(abs($flat_width * cos($angle) + $flat_height * sin($angle))); //Must be integer $height = ceil(abs($flat_width * sin($angle) + $flat_height * cos($angle))); //Must be integer return array($width, $height); }
public function genBarCode($code_id) { $text = $code_id; $font_size = 50; $height = 80; $width = 100; $im = ImageCreate($width, $height); $grey = ImageColorAllocate($im, 230, 230, 230); $black = ImageColorAllocate($im, 0, 0, 0); $text_bbox = ImageTTFBBox($font_size, 0, "font/FRE3OF9X.TTF", $text); $image_centerx = $width / 2; $image_centery = $height / 2; $text_x = $image_centerx - round($text_bbox[4] / 2); $text_y = $image_centery; ImageTTFText($im, $font_size, 0, $text_x, $text_y, $black, "font/FRE3OF9X.TTF", $text); ImagePng($im, "barcode/bc_{$code_id}.png"); ImageDestroy($im); //echo "<img src=image.png>"; /* $str="1234"; putenv('GDFONTPATH=' . realpath('.')); $font = "FRE3OF9X.TTF"; $image = imagecreate(100,30); $bg = imagecolorallocate($image,100,220,220); $black = imagecolorallocate($image, 0, 0, 0); imagettftext($image,28,0,2,25,$black,$font,$str); header("Content-type:image/png"); imagepng($image); imagedestroy($image); */ }
static function createWatermarkImage($source_dir, $destination_dir, $file_name, $delete_existing_file = false, $watermark_text = '', $args = array()) { global $wp_photo_gallery; if ($watermark_text === '') { $watermark_text = ' '; //get_site_url(); } $watermark_image_name = 'watermark_' . $file_name; $dest = $destination_dir . $watermark_image_name; if (file_exists($dest)) { if ($delete_existing_file === false) { return; } } $sourch_file = $source_dir . $file_name; $image_info = getimagesize($sourch_file); list($width, $height) = $image_info; $mime_type = strtolower($image_info['mime']); $desired_height = isset($args['watermark_height']) ? $args['watermark_height'] : ''; $desired_width = isset($args['watermark_width']) ? $args['watermark_width'] : ''; $font_size = isset($args['watermark_font_size']) ? $args['watermark_font_size'] : ''; $watermark_placement = isset($args['watermark_placement']) ? $args['watermark_placement'] : '0'; $watermark_opacity = isset($args['watermark_opacity']) ? $args['watermark_opacity'] : '35'; //$watermark_colour = isset($args['watermark_colour'])?$args['watermark_colour']:'ffffff'; //TODO - introduce in settings using a colour picker if ($desired_height != '') { //we have a portrait image so use the height as the maximum dimension if ($desired_height > $height) { $desired_height = $height; } //Check to make sure the watermarked image is not larger than the original $desired_width = floor($width * ($desired_height / $height)); } else { //we have a landscape image so use the width as the maximum dimension if (empty($desired_width)) { $desired_width = 600; } if ($desired_width > $width) { $desired_width = $width; } //Check to make sure the watermarked image is not larger than the original $desired_height = floor($height * ($desired_width / $width)); } if (empty($font_size)) { $font_size = 35; } if ($mime_type == 'image/jpeg' || $mime_type == 'image/pjpeg') { $image = imagecreatefromjpeg($sourch_file); } else { if ($mime_type == 'image/png') { $image = imagecreatefrompng($sourch_file); } } $font = WP_PHOTO_PATH . '/fonts' . DIRECTORY_SEPARATOR . 'arial.ttf'; $TextSize = ImageTTFBBox($font_size, 0, $font, $watermark_text) or die; $TextWidth = abs($TextSize[2]) + abs($TextSize[0]) + 8; //Added an extra 8 pixels because otherwise the watermark text appeared slightly cut-off on the RHS $TextHeight = abs($TextSize[7]) + abs($TextSize[1]); // Create Image for Text $image_p = ImageCreateTrueColor($TextWidth, $TextHeight); ImageSaveAlpha($image_p, true); ImageAlphaBlending($image_p, false); $bgText = imagecolorallocatealpha($image_p, 255, 255, 255, 127); imagefill($image_p, 0, 0, $bgText); $watermark_transparency = 127 - $watermark_opacity * 1.27; $color = 'ffffff'; //TODO - introduce in settings using a colour picker $rgb = WPPGPhotoGallery::hex2rgb($color, false); $TextColor = imagecolorallocatealpha($image_p, $rgb[0], $rgb[1], $rgb[2], $watermark_transparency); // Create Text on image imagettftext($image_p, $font_size, 0, 0, abs($TextSize[5]), $TextColor, $font, $watermark_text); $watermark_img_path = $image_p; imagealphablending($image_p, false); imagesavealpha($image_p, true); $sourcefile_width = imageSX($image); $sourcefile_height = imageSY($image); $watermarkfile_width = imageSX($image_p); $watermarkfile_height = imageSY($image_p); if ($watermark_placement == '0') { //Centre $dest_x = $sourcefile_width / 2 - $watermarkfile_width / 2; $dest_y = $sourcefile_height / 2 - $watermarkfile_height / 2; } elseif ($watermark_placement == '1') { //Top Left $dest_x = 5; $dest_y = 5; } elseif ($watermark_placement == '2') { //Top Right $dest_x = $sourcefile_width - $watermarkfile_width - 5; $dest_y = 5; } elseif ($watermark_placement == '3') { //Bottom Right $dest_x = $sourcefile_width - $watermarkfile_width - 5; $dest_y = $sourcefile_height - $watermarkfile_height - 5; } elseif ($watermark_placement == '4') { //Bottom Left $dest_x = 5; $dest_y = $sourcefile_height - $watermarkfile_height - 5; } else { //default - Centre $dest_x = $sourcefile_width / 2 - $watermarkfile_width / 2; $dest_y = $sourcefile_height / 2 - $watermarkfile_height / 2; } if ($watermark_placement != '5') { //Place the image according to the co-ordinates calculated from above imagecopy($image, $image_p, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height); } else { //Display watermark text as repeated grid $top = 20; while ($top < $sourcefile_height) { $left = 10; while ($left < $sourcefile_width) { imagecopy($image, $image_p, $left, $top, 0, 0, $TextWidth, $TextHeight); $left = $left + $TextWidth + 50; } $top = $top + $TextHeight + 50; } } /* create the physical watermarked image to its destination */ imagejpeg($image, $dest, 100); imagedestroy($image); //clean up some memory $resized = image_make_intermediate_size($source_dir . $watermark_image_name, $desired_width, $desired_height); //Use the WP function to resize the watermarked image to that specified in the settings if ($resized === false) { $wp_photo_gallery->debug_logger->log_debug('WPPGPhotoGallery::createWatermarkImage - image_make_intermediate_size failed and returned false!', 4); } else { rename($source_dir . $resized['file'], $source_dir . $watermark_image_name); //Since the above WP function uses a different naming convention we will change the name back to our convention } }
/** * Calculates the width & height dimensions of ImageTTFBBox(). * * Note: ImageTTFBBox() is unreliable with large font sizes * @param $wmSize * @param $fontAngle * @param $wmFontPath * @param $text * @return array */ function ImageTTFBBoxDimensions($wmSize, $fontAngle, $wmFontPath, $text) { $box = @ImageTTFBBox($wmSize, $fontAngle, $wmFontPath, $text) or die; $max_x = max(array($box[0], $box[2], $box[4], $box[6])); $max_y = max(array($box[1], $box[3], $box[5], $box[7])); $min_x = min(array($box[0], $box[2], $box[4], $box[6])); $min_y = min(array($box[1], $box[3], $box[5], $box[7])); return array("width" => $max_x - $min_x, "height" => $max_y - $min_y); }
static function createForText($text, &$font, $widthAdjustment, $heightAdjustment, $angle, $absoluteWidth = false, $absoluteHeight = false) { $Return = false; if (!$font instanceof eZImageFont) { return $Return; } if (!function_exists('ImageTTFBBox')) { eZDebug::writeError('ImageTTFBBox function not in PHP, check PHP compilation', 'ezimagetextlayer.php'); return $Return; } $bbox = ImageTTFBBox($font->pointSize(), $angle, $font->realFile(), $text); if (!$bbox) { return $Return; } $xmin = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]); $xmax = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]); $ymin = min($bbox[1], $bbox[3], $bbox[5], $bbox[7]); $ymax = max($bbox[1], $bbox[3], $bbox[5], $bbox[7]); $width = abs($xmax - $xmin); $height = abs($ymax - $ymin); $width += $widthAdjustment; $height += $heightAdjustment; if ($absoluteWidth !== false) { $width = $absoluteWidth; } if ($absoluteHeight !== false) { $height = $absoluteHeight; } $layer = new eZImageTextLayer(null, null, $width, $height, $font, $bbox, $text, $angle); $layer->create($width, $height, null); return $layer; }
function displayImage() { //{{{ $data = array(); $image_width = $image_height = 0; for ($i = 0; $i < $this->length; $i++) { //$char = substr($src, mt_rand(0,$srclen), 1); //$this->key .= $char; $char = $this->key[$i]; $size = mt_rand($this->min_font_size, $this->max_font_size); $angle = mt_rand($this->min_angle, $this->max_angle); $bbox = ImageTTFBBox($size, $angle, $this->fontFileName, $char); $char_width = max($bbox[2], $bbox[4]) - min($bbox[0], $bbox[6]); $char_height = max($bbox[1], $bbox[3]) - min($bbox[7], $bbox[5]); $image_width += $char_width + $this->char_padding; $image_height = max($image_height, $char_height); $data[] = array('char' => $char, 'size' => $size, 'angle' => $angle, 'height' => $char_height, 'width' => $char_width); } $image_width += $this->x_padding * 2; $image_height = $image_height * 1.5 + 2; $im = ImageCreate($image_width, $image_height); $r = 51 * mt_rand(4, 5); $g = 51 * mt_rand(4, 5); $b = 51 * mt_rand(4, 5); $color_bg = ImageColorAllocate($im, $r, $g, $b); $r = 51 * mt_rand(3, 4); $g = 51 * mt_rand(3, 4); $b = 51 * mt_rand(3, 4); $color_line0 = ImageColorAllocate($im, $r, $g, $b); $r = 51 * mt_rand(3, 4); $g = 51 * mt_rand(3, 4); $b = 51 * mt_rand(3, 4); $color_line1 = ImageColorAllocate($im, $r, $g, $b); $r = 51 * mt_rand(1, 2); $g = 51 * mt_rand(1, 2); $b = 51 * mt_rand(1, 2); $color_text = ImageColorAllocate($im, $r, $g, $b); $color_border = ImageColorAllocate($im, 0, 0, 0); // make the random background lines for ($l = 0; $l < 10; $l++) { $c = 'color_line' . $l % 2; $lx = mt_rand(0, $image_width + $image_height); $lw = mt_rand(0, 3); if ($lx > $image_width) { $lx -= $image_width; ImageFilledRectangle($im, 0, $lx, $image_width - 1, $lx + $lw, ${$c}); } else { ImageFilledRectangle($im, $lx, 0, $lx + $lw, $image_height - 1, ${$c}); } } // output each character $pos_x = $this->x_padding + $this->char_padding / 2; foreach ($data as $d) { $pos_y = ($image_height + $d['height']) / 2; ImageTTFText($im, $d['size'], $d['angle'], $pos_x, $pos_y, $color_text, $this->fontFileName, $d['char']); $pos_x += $d['width'] + $this->char_padding; } // a nice border ImageRectangle($im, 0, 0, $image_width - 1, $image_height - 1, $color_border); // display it switch ($this->output_type) { case 'jpeg': Header('Content-type: image/jpeg'); ImageJPEG($im, NULL, 100); break; case 'png': default: Header('Content-type: image/png'); ImagePNG($im); break; } ImageDestroy($im); }
function waterMarkFont() { if ($this->param['water_mark_color']) { $color = $this->param['water_mark_color']; } else { $color = '#000000'; } $r = hexdec(substr($color, 1, 2)); $g = hexdec(substr($color, 3, 2)); $b = hexdec(substr($color, 5, 2)); if ($this->param['water_mark_opacity'] > 0 && $this->param['water_mark_opacity'] < 100) { $fontcolor = imagecolorallocatealpha($this->image, $r, $g, $b, $this->param['water_mark_opacity']); } else { $fontcolor = imagecolorallocate($this->image, $r, $g, $b); } $box = ImageTTFBBox($this->param['water_mark_fontsize'], $this->param['water_mark_angle'], $this->param['water_mark_font'], $this->param['water_mark_string']); $ground_w = $this->getWidth(); $ground_h = $this->getHeight(); $h = max($box[1], $box[3]) - min($box[5], $box[7]); $w = max($box[2], $box[4]) - min($box[0], $box[6]); $ax = min($box[0], $box[6]) * -1; $ay = min($box[5], $box[7]) * -1; switch ($this->param['water_mark_pos']) { case 0: //随机 $posX = rand(5, $ground_w - $w - 5); $posY = rand(5, $ground_h - $h - 5); break; case 1: //1为顶端居左 $posX = 5; $posY = 5; break; case 2: //2为顶端居中 $posX = ($ground_w - $w) / 2; $posY = 5; break; case 3: //3为顶端居右 $posX = $ground_w - $w - 5; $posY = 5; break; case 4: //4为中部居左 $posX = 5; $posY = ($ground_h - $h) / 2; break; case 5: //5为中部居中 $posX = ($ground_w - $w) / 2; $posY = ($ground_h - $h) / 2; break; case 6: //6为中部居右 $posX = $ground_w - $w - 5; $posY = ($ground_h - $h) / 2; break; case 7: //7为底端居左 $posX = 5; $posY = $ground_h - $h - 5; break; case 8: //8为底端居中 $posX = ($ground_w - $w) / 2; $posY = $ground_h - $h - 5; break; case 9: //9为底端居右 $posX = $ground_w - $w - 5; $posY = $ground_h - $h - 5; break; default: //随机 $posX = rand(5, $ground_w - $w - 5); $posY = rand(5, $ground_h - $h - 5); break; } imagettftext($this->image, $this->param['water_mark_fontsize'], $this->param['water_mark_angle'], $posX + $ax, $posY + $ay, $fontcolor, $this->param['water_mark_font'], $this->param['water_mark_string']); }
function TTFBBoxSize($size, $angle, $font, $string) { //Assume angle < 90 $arr = ImageTTFBBox($size, 0, $font, $string); $flat_width = $arr[0] - $arr[2]; $flat_height = abs($arr[3] - $arr[5]); // for 90deg: // $height = $arr[5] - $arr[7]; // $width = $arr[2] - $arr[4]; $angle = deg2rad($angle); $width = ceil(abs($flat_width * cos($angle) + $flat_height * sin($angle))); //Must be integer $height = ceil(abs($flat_width * sin($angle) + $flat_height * cos($angle))); //Must be integer return array($width, $height); }
function DrawTitleAxisY() { $posarr = ImageTTFBBox($this->axis_title_size, 90, $this->font, $this->title_axis_y); $stringheight = abs($posarr[3]) - abs($posarr[1]); $stringwidth = abs($posarr[6]) - abs($posarr[0]); $stringypos = $this->chart_area[3] - $this->chart_area[1]; $stringypos = $stringypos / 2 + $stringheight; $stringxpos = $stringwidth * 2; ImageTTFText($this->img, $this->axis_title_size, 90, $stringxpos, $stringypos, $this->font_color, $this->font, $this->title_axis_y); }
function StrokeText($x, $y, $txt, $dir = 0) { if (!is_numeric($dir)) { die("JpGraph Error: Direction for text most be given as an angle between 0 and 90."); } if ($this->font_family >= FONT0 && $this->font_family <= FONT2_BOLD) { // Internal font if (is_numeric($dir) && $dir != 90 && $dir != 0) { die("JpGraph Error: Internal font does not support drawing text at arbitrary angle. Use TTF fonts instead."); } if (($this->font_family == FONT1 || $this->font_family == FONT2) && $this->font_style == FS_BOLD) { ++$this->font_family; } $h = $this->GetFontHeight($txt); $w = $this->GetTextWidth($txt); if ($this->text_halign == "right") { $x -= $dir == 0 ? $w : $h; } elseif ($this->text_halign == "center") { $x -= $dir == 0 ? $w / 2 : $h / 2; } if ($this->text_valign == "top") { $y += $dir == 0 ? $h : $w; } elseif ($this->text_valign == "center") { $y += $dir == 0 ? $h / 2 : $w / 2; } if ($dir == 90) { imagestringup($this->img, $this->font_family, $x, $y, $txt, $this->current_color); } else { imagestring($this->img, $this->font_family, $x, $y - $h + 1, $txt, $this->current_color); } } else { // TTF font $file = $this->ttf->File($this->font_family, $this->font_style); //echo "FF = $this->font_family, file=$file"; $angle = $dir; $bbox = ImageTTFBBox($this->font_size, $angle, $file, $txt); if ($this->text_halign == "right") { $x -= $bbox[2] - $bbox[0]; } elseif ($this->text_halign == "center") { $x -= ($bbox[4] - $bbox[0]) / 2; } elseif ($this->text_halign == "topanchor") { $x -= $bbox[4] - $bbox[0]; } elseif ($this->text_halign == "left") { $x += -($bbox[6] - $bbox[0]); } if ($this->text_valign == "top") { $y -= $bbox[5]; } elseif ($this->text_valign == "center") { $y -= ($bbox[5] - $bbox[1]) / 2; } elseif ($this->text_valign == "bottom") { $y -= $bbox[1]; } // Use lower left of bbox as fix-point, not the default baselinepoint. // $x -= $bbox[0]; ImageTTFText($this->img, $this->font_size, $angle, $x, $y, $this->current_color, $file, $txt); } }
function _StrokeTTF($x, $y, $txt, $dir, $paragraph_align, &$aBoundingBox, $debug = false) { // Setup default inter line margin for paragraphs to be // 3% of the font height. $ConstLineSpacing = 0.03; // Remember the anchor point before adjustment if ($debug) { $ox = $x; $oy = $y; } if (!preg_match('/\\n/', $txt) || $dir > 0 && preg_match('/\\n/', $txt)) { // Format a single line $txt = $this->AddTxtCR($txt); $bbox = $this->GetBBoxTTF($txt, $dir); $width = $this->GetBBoxWidth($txt, $dir); $height = $this->GetBBoxHeight($txt, $dir); // The special alignment "basepoint" is mostly used internally // in the library. This will put the anchor position at the left // basepoint of the tetx. This is the default anchor point for // TTF text. if ($this->text_valign != 'basepoint') { // Align x,y ot lower left corner of bbox if ($this->text_halign == 'right') { $x -= $width; $x -= $bbox[0]; } elseif ($this->text_halign == 'center') { $x -= $width / 2; $x -= $bbox[0]; } elseif ($this->text_halign == 'baseline') { // This is only support for text at 90 degree !! // Do nothing the text is drawn at baseline by default } if ($this->text_valign == 'top') { $y -= $bbox[1]; // Adjust to bottom of text $y += $height; } elseif ($this->text_valign == 'center') { $y -= $bbox[1]; // Adjust to bottom of text $y += $height / 2; } elseif ($this->text_valign == 'baseline') { // This is only support for text at 0 degree !! // Do nothing the text is drawn at baseline by default } } ImageTTFText($this->img, $this->font_size, $dir, $x, $y, $this->current_color, $this->font_file, $txt); // Calculate and return the co-ordinates for the bounding box $box = $this->imagettfbbox_fixed($this->font_size, $dir, $this->font_file, $txt); $p1 = array(); for ($i = 0; $i < 4; ++$i) { $p1[] = round($box[$i * 2] + $x); $p1[] = round($box[$i * 2 + 1] + $y); } $aBoundingBox = $p1; // Debugging code to highlight the bonding box and bounding rectangle // For text at 0 degrees the bounding box and bounding rectangle are the // same if ($debug) { // Draw the bounding rectangle and the bounding box $p = array(); $p1 = array(); for ($i = 0; $i < 4; ++$i) { $p[] = $bbox[$i * 2] + $x; $p[] = $bbox[$i * 2 + 1] + $y; $p1[] = $box[$i * 2] + $x; $p1[] = $box[$i * 2 + 1] + $y; } // Draw bounding box $this->PushColor('green'); $this->Polygon($p1, true); $this->PopColor(); // Draw bounding rectangle $this->PushColor('darkgreen'); $this->Polygon($p, true); $this->PopColor(); // Draw a cross at the anchor point $this->PushColor('red'); $this->Line($ox - 15, $oy, $ox + 15, $oy); $this->Line($ox, $oy - 15, $ox, $oy + 15); $this->PopColor(); } } else { // Format a text paragraph $fh = $this->GetFontHeight(); // Line margin is 25% of font height $linemargin = round($fh * $ConstLineSpacing); $fh += $linemargin; $w = $this->GetTextWidth($txt); $y -= $linemargin / 2; $tmp = preg_split('/\\n/', $txt); $nl = count($tmp); $h = $nl * $fh; if ($this->text_halign == 'right') { $x -= $dir == 0 ? $w : $h; } elseif ($this->text_halign == 'center') { $x -= $dir == 0 ? $w / 2 : $h / 2; } if ($this->text_valign == 'top') { $y += $dir == 0 ? $h : $w; } elseif ($this->text_valign == 'center') { $y += $dir == 0 ? $h / 2 : $w / 2; } // Here comes a tricky bit. // Since we have to give the position for the string at the // baseline this means thaht text will move slightly up // and down depending on any of it's character descend below // the baseline, for example a 'g'. To adjust the Y-position // we therefore adjust the text with the baseline Y-offset // as used for the current font and size. This will keep the // baseline at a fixed positoned disregarding the actual // characters in the string. $standardbox = $this->GetTTFBBox('Gg', $dir); $yadj = $standardbox[1]; $xadj = $standardbox[0]; $aBoundingBox = array(); for ($i = 0; $i < $nl; ++$i) { $wl = $this->GetTextWidth($tmp[$i]); $bbox = $this->GetTTFBBox($tmp[$i], $dir); if ($paragraph_align == 'left') { $xl = $x; } elseif ($paragraph_align == 'right') { $xl = $x + ($w - $wl); } else { // Center $xl = $x + $w / 2 - $wl / 2; } // In theory we should adjust with full pre-lead to get the lines // lined up but this doesn't look good so therfore we only adjust with // half th pre-lead $xl -= $bbox[0] / 2; $yl = $y - $yadj; //$xl = $xl- $xadj; ImageTTFText($this->img, $this->font_size, $dir, $xl, $yl - ($h - $fh) + $fh * $i, $this->current_color, $this->font_file, $tmp[$i]); // echo "xl=$xl,".$tmp[$i]." <br>"; if ($debug) { // Draw the bounding rectangle around each line $box = @ImageTTFBBox($this->font_size, $dir, $this->font_file, $tmp[$i]); $p = array(); for ($j = 0; $j < 4; ++$j) { $p[] = $bbox[$j * 2] + $xl; $p[] = $bbox[$j * 2 + 1] + $yl - ($h - $fh) + $fh * $i; } // Draw bounding rectangle $this->PushColor('darkgreen'); $this->Polygon($p, true); $this->PopColor(); } } // Get the bounding box $bbox = $this->GetBBoxTTF($txt, $dir); for ($j = 0; $j < 4; ++$j) { $bbox[$j * 2] += round($x); $bbox[$j * 2 + 1] += round($y - ($h - $fh) - $yadj); } $aBoundingBox = $bbox; if ($debug) { // Draw a cross at the anchor point $this->PushColor('red'); $this->Line($ox - 25, $oy, $ox + 25, $oy); $this->Line($ox, $oy - 25, $ox, $oy + 25); $this->PopColor(); } } }
function draw() { putenv('GDFONTPATH=' . APPLICATION_PATH . '/../library/fonts'); $width = 0; $height = 0; $offset_x = 0; $offset_y = 0; $bounds = array(); $image = ""; $bounds = ImageTTFBBox($this->size, $this->rot, $this->font, "W"); if ($this->rot < 0) { $font_height = abs($bounds[7] - $bounds[1]); } else { if ($this->rot > 0) { $font_height = abs($bounds[1] - $bounds[7]); } else { $font_height = abs($bounds[7] - $bounds[1]); } } $bounds = ImageTTFBBox($this->size, $this->rot, $this->font, $this->msg); if ($this->rot < 0) { $width = abs($bounds[4] - $bounds[0]); $height = abs($bounds[3] - $bounds[7]); $offset_y = $font_height; $offset_x = 0; } else { if ($this->rot > 0) { $width = abs($bounds[2] - $bounds[6]); $height = abs($bounds[1] - $bounds[5]); $offset_y = abs($bounds[7] - $bounds[5]) + $font_height; $offset_x = abs($bounds[0] - $bounds[6]); } else { $width = abs($bounds[4] - $bounds[6]); $height = abs($bounds[7] - $bounds[1]); $offset_y = $font_height; $offset_x = 0; } } $image = imagecreate($width + $this->pad * 2 + 1, $height + $this->pad * 2 + 1); $background = ImageColorAllocate($image, $this->bg_red, $this->bg_grn, $this->bg_blu); $foreground = ImageColorAllocate($image, $this->red, $this->grn, $this->blu); if ($this->transparent) { ImageColorTransparent($image, $background); } ImageInterlace($image, false); ImageTTFText($image, $this->size, $this->rot, $offset_x + $this->pad, $offset_y + $this->pad, $foreground, $this->font, $this->msg); imagePNG($image); }