search
HomeBackend DevelopmentPHP TutorialPHP中创建图像并绘制文字的例子_php技巧

在图像中显示的文字也需要按坐标位置画上去。在PHP中不仅支持比较多的字体库,而且提供了非常灵活的文字绘制方法。例如,在图中绘制缩放、倾斜、旋转的文字等。可以使用imageString()、imageStringUP()或imageChar()等函数使用的字体文字绘制到图像中。这些函数的原型如下所示:

复制代码 代码如下:

bool imagestring(resource $image,int $font,int $x ,int $y,string $s,int $color)              //水平地画一行字符串
bool imagestringup(resource $image,int $font,int $x ,int $y,string $s,int $color)                 //垂直地画一行字符串
bool imagechar(resource $image,int $font,int $x ,int $y,char $c,int $color)                //水平地画一个字符
bool imagecharup(resource $image,int $font,int $x ,int $y,char $c,int $color)                 //垂直地画一个字符

在上面列出来的四个函数中,前两个函数imageString()和imageStringUP()分别用来向图像中水平和垂直输出一行字符串,而后两个函数imageChar()和imageCharUP()分别用来向图像中水平和垂直输出一个字符。虽然这四个函数有所差异,但调用方式类似。它们都是在$image图像中绘制由第五个参数指定的字符,绘制的位置都是从坐标($x,$y)开始输出。如果是水平地面画一行字符串则是从左向右输出,而垂直地画一行字符串则是从下而上输出。这些函数都可以通过最后一个参数$color给出文字的颜色。第二个参数$font则给出了文字字体标识符,其值为整数1、2、3、4或5,则是使用内置的字体,数字越大则输出的文字尺寸就越大。下面是在一个图像中输出文字的示例:

复制代码 代码如下:

$im = imagecreate(150, 150);
 
$bg = imagecolorallocate($im, 255, 255, 255); //设置画布的背景为白色
$black = imagecolorallocate($im, 0, 0, 0); //设置一个颜色变量为黑色
 
$string = "LAMPBrother"; //在图像中输出的字符
 
imagestring($im, 3, 28, 70, $string, $black); //水平的将字符串输出到图像中
imagestringup($im, 3, 59, 115, $string, $black); //垂直由下而上输到图像中
for($i=0,$j=strlen($string);$i imagechar($im, 3, 10*($i+1),10*($j+2),$string[$i],$black); //向下倾斜输出每个字符
imagecharup($im, 3, 10*($i+1),10*($j+2),$string[$i],$black); //向上倾斜输出每个字符
}
 
header('Content-type:image/png');
imagepng($im);
?>

通过上面介绍的四个函数输出内置的字体外,还可以使用imageTtfText()函数,输出一种可以缩放的与设备无关的TrueType字体。TrueType是用数学函数描述字体轮廓外形,即可以用做打印字体,又可以用作屏幕显示,各种操作系统都可以兼容这种字体。由于它是由指令对字形进行描述,因此它与分辨率无关,输出时总是按照打印机的分辨率输出。无论放大或是缩小,字体总是光滑的,不会有锯齿出现。例如在Windows系统中,字体库所在的文件夹C:\WINDOWS\Fonts下,对TrueType字体都有标注,如simsun.ttf为TrueType字体中的“宋体”。imageTtfText()函数的原型如下所示:

复制代码 代码如下:

array imagettftext(resource $image,float $size ,float $angle,int $x,int $y,int $color ,string $fontfile,string $text)

该函数需要多个参数,其中参数$image需要提供一个图像资源。参数$size用来设置字体大小,根据GD库版本不同,应该以像素大小指定(GD1)或点大小(GD2)。参数$angle是角度制表示的角度,0º为从左向右读的文本,更高数值表示逆时针旋转。例如90º表示从下向上读的文本。并由($x,$y)两个参数所表示的坐标,定义了一个字符的基本点,大概是字符的左下角。而这和imagestring()函数有所不同,其($x,$y)坐标定义了第一个字符的左上角。参数$color指定颜色索引。使用负的颜色索引值具有关闭防锯齿的效果。参见$fontfile是想要使用的TrueType字体的路径。根据PHP所使用的GD库的不同,当fontfil没有以“/”开头时则“.ttf”将被加到文件名之后,并且会在库定义字体路径中尝试搜索该文件名。最后一个参数$text指定需要输出的文本字符串,可以包含十进制数字化字符表示(形式为:€)来访问字体中超过位置127的字符。UTF-8编码的字符串可以直接传递。如果字符串中使用的某个字符不被字体支持,一个空心矩形将替换该字符。

imagettftext()函数返回一个含有8个单元的数组,表示了文本外框的四个角,顺序为左下角,右下角,右上角,左上角。这些点是相对于文本的而和角度无关,因此“左上角”指的是以水瓶方向看文字时其左上角。我们通过在下例中的脚本,生成一个白色的400X30像素的PNG图片,其中有黑色(带灰色阴影)“宋体”字体写的“回忆经典!”代码如下所示:

复制代码 代码如下:

$im = imagecreatetruecolor(400, 30);            //创建400 30像素大小的画布
 
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
 
imagefilledrectangle($im, 0, 0, 399, 29, $white);       //输出一个使用白色填充的矩形作为背景
 
//如果有中文输出,需要将其转码,转换为UTF-8的字符串才可以直接传递
$text = iconv("GB2312", "UTF-8", "回忆经典");
 
//设定字体,将系统中与simsun.ttc对应的字体复制到当前目录下
$font = 'simsun.ttc';
 
imagettftext($im, 20, 0, 12, 21, $grey, $font, $text);      //输出一个灰色的字符串作为阴影
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);         //在阴影上输出一个黑色的字符串
 
header("Content-type: image/png");
imagepng($im);
 
imagedestroy($im);
 
?>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.