如何使用PHP GD库向文本添加文本 [英] How to add text to an image with PHP GD library

查看:121
本文介绍了如何使用PHP GD库向文本添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <?php 
header(Content-Type:图像/ JPEG);
$ im = ImageCreateFromGif(photo.gif);
$ black = ImageColorAllocate($ im,255,255,255);
$ start_x = 10;
$ start_y = 20;
Imagettftext($ im,12,0,$ start_x,$ start_y,$ black,'verdana.ttf',text to write);
Imagejpeg($ im,'',100);
ImageDestroy($ im);
?>

图像输出文件为image.php,代码如下

 < html> 
< head>
< / head>
< body>
< img src =http://localhost/image_creator.php/>
< / body>

< / html>

当我运行image.php时,我只是得到一个空白页面。为什么会这样?

解决方案

使用此功能可将文字添加到图片中(从 PHP for Kids

<?php 
//设置内容类型
头('Content-type:image / jpeg');

//从现有文件创建图像
$ jpg_image = imagecreatefromjpeg('sunset.jpg');

//为文本分配颜色
$ white = imagecolorallocate($ jpg_image,255,255,255);

//将路径设置为字体文件
$ font_path ='font.TTF';

//将文本设置为打印图像
$ text =这是日落!;

//在文本上打印文本
imagettftext($ jpg_image,25,0,75,300,$ white,$ font_path,$ text);

//发送图片到浏览器
imagejpeg($ jpg_image);

//清除内存
imagedestroy($ jpg_image);
?>


I have image creation code in image_creator.

<?php
header("Content-Type: image/jpeg");
$im = ImageCreateFromGif("photo.gif"); 
$black = ImageColorAllocate($im, 255, 255, 255);
$start_x = 10;
$start_y = 20;
Imagettftext($im, 12, 0, $start_x, $start_y, $black, 'verdana.ttf', "text to write");
Imagejpeg($im, '', 100);
ImageDestroy($im);
?> 

The file for image output is image.php and has below code

<html>
<head>
</head>
<body>
    <img src="http://localhost/image_creator.php"/> 
</body>

</html>

When I run image.php, I just get a blank page. Why is it so?

解决方案

Use this to add text to image (copied from PHP for Kids)

<?php
      //Set the Content Type
      header('Content-type: image/jpeg');

      // Create Image From Existing File
      $jpg_image = imagecreatefromjpeg('sunset.jpg');

      // Allocate A Color For The Text
      $white = imagecolorallocate($jpg_image, 255, 255, 255);

      // Set Path to Font File
      $font_path = 'font.TTF';

      // Set Text to Be Printed On Image
      $text = "This is a sunset!";

      // Print Text On Image
      imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

      // Send Image to Browser
      imagejpeg($jpg_image);

      // Clear Memory
      imagedestroy($jpg_image);
    ?> 

这篇关于如何使用PHP GD库向文本添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆