百科狗-知识改变命运!
--

imagestring() - gd函数(图像处理)

梵高12个月前 (11-21)阅读数 18#技术干货
文章标签字符串

imagestring()

(PHP 4, PHP 5, PHP 7)

水平地画一行字符串

说明

imagestring(resource $image,int $font,int $x,int $y,string $s,int $col): bool

imagestring()用$col颜色将字符串$s画到$image所代表的图像的$x,$y坐标处(这是字符串左上角坐标,整幅图像的左上角为 0,0)。如果$font是 1,2,3,4 或 5,则使用内置字体。

imagestring() - gd函数(图像处理)

imagestring()例子

参见imageloadfont()和imagettftext()。

Some fun with imagestring:
This function is a product of too much time..
It opens an image and create a new image with one letter instead of a pixel.

Have fun :)
Here is a function with similar declaration of imagestring() but who handles whitespaces (It creates new lines and 4 spaces instead of \n and \t) and image's size limits 
// Convert e-mail to image (png)
function convertEmailToImg ($aValue, $aRed, $aGreen, $aBlue, $aAlphaF=0, $aAlphaB=127, $aFontSize=4)
{
  $img= imagecreatetruecolor (imagefontwidth ($aFontSize) * strlen ($aValue), imagefontheight ($aFontSize));
  imagesavealpha ($img, true);
  imagefill ($img, 0, 0, imagecolorallocatealpha ($img, 0, 0, 0, $aAlphaB));
  imagestring ($img, $aFontSize, 0, 0, $aValue, imagecolorallocatealpha ($img, $aRed, $aGreen, $aBlue, $aAlphaF));
  ob_start ();
  imagepng ($img);
  imagedestroy ($img);
  return base64_encode (ob_get_clean ());
}
// Example
$imgString= convertEmailToImg ('contact@example.com', 0, 0, 255, 0, 127, 4);
I like this better than "tjpoe at cableaz dot com"'s function for wrapping text to fit width (auto-adjusts height as needed) since it doesn't only do 1 word per line.
function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
 if (strlen($color) != 6) $color = 000000;
 $int = hexdec($color);
 $h = imagefontheight($font);
 $fw = imagefontwidth($font);
 $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
 $lines = count($txt);
 $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
 $bg = imagecolorallocate($im, 255, 255, 255);
 $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
 $y = 0;
 foreach ($txt as $text) {
  $x = (($w - ($fw * strlen($text))) / 2);
  imagestring($im, $font, $x, $y, $text, $color);
  $y += ($h + $space);
 }
 header('Content-type: image/jpeg');
 die(imagejpeg($im));
}
A simple example:
To make one line of text fit in the image.

I use something like this for spamprotection of my visitors (pass userid as an url-parameter for this php)
i modified the centering functions and created this which centers each word on it's own line. You can adjust the spacing with the $valign var. currently no implimentation if text is too large for image. strings are tokenized by space, but can obviously be changed. 
function ImageStringWrap($image, $font, $text, $color)
{
 $fontwidth = ImageFontWidth($font);
 $fontheight = ImageFontHeight($font);
 $words= str_word_count($text);
 if ($words > 1){
  $string=array(strtok($text,' '));
  for ($i = 1 ; $i strtok(' ')));
  }
 }
 else
  $string=$text;
 $vspace=4;
 $y=((imagesy($image)-($fontheight*$words)-($words*$vspace))/2);
 foreach($string as $st){
  $x=((imagesx($image)-($fontwidth * strlen($st)))/2);
  ImageString($image,$font,$x,$y,$st,$color);
  $y+=($fontheight+$vspace);
 }
}
hope this is helpful
//simple hello world 
Width ImageString, the strings you draw are not automatically wrapped width the edge of the image. You may use this function to automatically wrap them:
function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth)
{
  $fontwidth = ImageFontWidth($font);
  $fontheight = ImageFontHeight($font);
  if ($maxwidth != NULL) {
    $maxcharsperline = floor($maxwidth / $fontwidth);
    $text = wordwrap($text, $maxcharsperline, "\n", 1);
   }
  $lines = explode("\n", $text);
  while (list($numl, $line) = each($lines)) {
    ImageString($image, $font, $x, $y, $line, $color);
    $y += $fontheight;
   }
}
So, in particular, if you want to wrap a text with the edge of the Image, you may do:
ImageStringWrap($img, $font, 0, $y, $text, $color, ImageSX($img) );
Creates a box of text. Has horizontal and vertical alignment, box arguments, and custom leading. I submitted this to the manual in 2003 actually, but it disappeared after a year or so (not sure why). Here it is again. 
Simple script to convert a string (such as an email addresses) to a transparent image.
Usage: 
">
From a spambot's point of view, they see:

Optional parameters:
  font_size: 1 to 5, with the default at 3
  R/G/B: the font color, in hex.
Usage:
&font_size=4&R=FF&G=FF&B=00"> 
// Example of use...
// This is a simple function to output text to an image
// which is centered (as much as I want to do by eye)
// and wrapped
//  Just remember that all the sizes are guessed
// doesn't cut on the space (only on number of characters)
// or change color of text, but this isn't for that...
function imageCenterString( $imgw, $imgh,
  $image_text = '', $text_size=5 )
{
  $im = imagecreate( $imgw, $imgh );
  
  // white background and blue text
  $bg = imagecolorallocate($im, 255, 255, 255);
  $textcolor = imagecolorallocate($im, 0, 0, 0);
  
  $t_h = $t_w = $t_x = $t_y = 0;
  $base_w =9; $base_h = 16;
  $m = 0.88;
  switch ( $text_size )
  {
   case 1: $t_w = $base_w*pow(($m*.98),4);
     $t_h = $base_h*pow(($m*.98),4);
     break;
   case 2: $t_w = $base_w*pow($m,3);
     $t_h = $base_h*pow($m,3);
     break;
   case 3: $t_w = $base_w*pow($m,2);
     $t_h = $base_h*pow($m,2);
     break;
   case 4: $t_w = $base_w*$m;
     $t_h = $base_h*$m;
     break;
   case 5: $t_w = $base_w;
     $t_h = $base_h;
     break;
   default:
     if ( $text_size >= 5 ) // set to 5
     {  $t_w = $base_w; $t_h = $base_h; }
     if ( $text_size  0; $i += $max)
  {
   array_push($text_array, substr($image_text,0,$max));
   if ( strlen($image_text) >= $max )
   {  $image_text = substr($image_text,$max); }
   else
   {  $image_text = ''; }
  }
  
  $t_y = ($imgh/2) - ($t_h*count($text_array)/2);
  foreach ( $text_array as $text )
  {
   $t_x = ($imgw/2)-($t_w*strlen($text)/2);
   imagestring($im, $text_size, $t_x, $t_y,
     $text, $textcolor);
   $t_y += $t_h;
  }
  // output the image
  header("Content-type: image/gpeg");
  imagejpeg($im);
}
If you are looking to center the text, use the following function; I'm not promising perfection...
function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
  $textWidth = imagefontwidth( $font ) * strlen( $str );
  $xLoc = ( $xMax - $xMin - $textWidth ) / 2 + $xMin + $font;
  imagestring( $img, $font, $xLoc, $y, $str, $col );
}
There is an error in "tjpoe at cableaz dot com" 's function ImageStringWrap. Instead of 
  else
      $string = $text;
there should be
   else
      $string = array($text);
for function to work for strings with only one word. Otherwise it works like a charm, thanks.
Here is a small bit I made for writing to a image from right to left when you are limited to imagestring() 
Its just an easy function to write an string in the middle of a picture. 
The built-in fonts used to be in latin-2 (iso8859-2) encoding. For some time, they are in latin-1 (iso8859-1) encoding. There is no way to change the encoding at all. If you need to use any other encoding, you have to use TrueType fonts.
If you find that you are getting two characters on the end of your imageString that look like a Y and an upside down L then they're probably representations of CR/LF. Try trim()ing the string before outputting it. (I was sooo sure this was a bug )
I created an alternative using the function imagechar to create a string of an image. The below function below was used to create an image the same height and width of the text string. It is used on my website to mask users email addresses. 
If you have any problem with CentralEurope's words, for example : ľščťžýáíéúäňôď, I am try this problem by iconv() function. 
I've made a little modification of the (quite usefull) imagestringcutted function (when align=center, it doesn't work well for me if x1!=0) so juste replace the last line with : 
Here's a simple function for creating an aligned string which is cutted to match the space between $x1 and $x2

Usage:

Will create a string $text, which is cutted if it's too long to match between $x1 and $2, on $img with font $font and color $color at height $y and with align to $align.
Hope it will help some people.
Sorry for my bad English.
My version of the centered string, it decreases the font number (since I've noticed smaller numbers are smaller fonts) until 1 if the string won't fit. Then it will give up. 
Drawing a string as an image is a handy way to disguise an eMail address so spam sniffers can't get it as easily. The only catch to creating a dynamic image with your eMail in it is the eMail to be displayed must be passed via the query string to enable static HTML to use it. So, the eMail must be encrypted slightly in order to not defeat the purpose of not typing your eMail address outright. I wrote the following script to do so:
Save the following as email.php

If the script is called without an eMail address, it outputs a 2x2 transparent image.
To call the script to generate the eMail "user@home.com", the HTML tag would be:

To 'encrypt' the eMail address to pass to the script, write the address backwards and replace "." with "[dot]" and "@" with "[at]". It's not the most ironclad protection, but it thwarts most casual eMail sniffers.
this is a function that is based on imagestring but it produces text in the center of an image i hope it helps :D 
When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.
Same function as above but it can display multi-line strings. 
hello, I noticed that if you put a rand(3,5) it will put random sizes of font to each character put on the image. this is very useful when programming captchas for anti-spam form verification.
If you are looking for a way to generate a "CAPTCHA" image for a form verification (to verify it is not a robot), have a look at this : http://blog.theoconcept.com/static/distortion/
It gives an animated image with the parameter string, with distortion, here is an example :
http://blog.theoconcept.com/static/distortion/distortion.php
(*) You'll need GD + Freetype support
(**) You'll need ImageMagick on the machine
There is a small error in the function for horizontal and vertical centering by "jurgen dot vanoosterwijck at pandora dot be"
the line 
 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);
should be
 $cy = (imagesy($img)/2) - (imagefontheight($font)/2);
This code produces a png image of the text within the query. It autofits to the length of the string. 
Usage: http://yoursite.com/text.php?abcdefg+hijk
Use + to produce a space in the image. The + can be excaped with a carat (^). Most other symbols work fine in the query string, like the ?.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)