用php在图片上写字

an9ryfr09 2006-09-29 03:34:54
今天上班不怎么忙,封装了个在图片上写字的类。请大家指教并来扩展它的功能。这个类还算抽象,功能不太强,具体的大家可以继承之后再扩展。
目前不支持中文写入,如果需要支持中文写入,需要把汉字转为utf-8编码。
可以用它来做注册验证的随机码,只需要再写个产生随机序列的方法。

/**
* @author injection(injection.mail@gmail.com)
* @package ImageContext.class.php
* @var object mImages 图片相关的数据
*/
class drawImg{
var $mImages;

/**
* 设定本页面类型为图片类型
*/
function __construct(){
header("content-type:image/gif");
}

/**
* 设置图片源
*
* @param string $filename
* @example 'c://mypic/mypic.gif' or 'mypic.gif'
*/
function setImage( $filename ){
$this->mImages->filename = imagecreatefromgif( $filename );
}

/**
* 设置写入文字的字体
*
* @param string $font
* @example simhei.ttf
*/
function setFont( $font ){
$this->mImages->font = $font;
}


/**
* 设置写入的文字
*
* @param string $context
* @example test
*/
function setContext( $context ){
$this->mImages->context = $context;
}

/**
* 设置写入黑白的具体数值
*
* @param string $white
* @example 255,255,255
* @param string $black
* @example 0,0,0
*/
function setColor( $white,$black ){
$this->mImages->white = imagecolorallocate( $this->mImages->filename,$white );
$this->mImages->black = imagecolorallocate( $this->mImages->filename,$black );
}

/**
* 根据参数类型获取mImages对象属性或对象的信息
*
* @param enum 参数列表:filename,font,context,all
* @return 一个mImages的一个属性或mImages这个对象
*/
function getImageInfo( $type="all" ){
if( $type != "all")
return $this->mImages->$type;
else
return $this->mImages;
}


/**
* 将文字写入图片
*
* @param int $size 字体大小
* @param int $angle 起始角度
* @param int $x 第一个字符的基本点(大概是字符的左下角)
* @param int $y Y坐标。它设定了字体基线的位置,不是字符的最底端
* @param enum $ 值为white或black
*/
function draw( $size,$angle,$x,$y,$color ){
imagettftext( $this->mImages->filename,$size,$angle,$x,$y,$this->mImages->$color,$this->mImages->font,$this->mImages->context );
imagegif( $this->mImages->filename );
}

/**
* 释放图片源
*/
function unsetImage(){
imagedestroy( $this->mImages->filename );
}

/**
* 释放本对象
*/
function __destruct(){
unset( $this );
}
}

/* sample */
$image = new drawImg();
$image->setImage( 'mypic.gif' );
$image->setFont( 'simhei.ttf' );
$image->setContext( 'test' );
@$image->setColor('255,255,255','0,0,0');
$image->draw( 20,0,0,20,'black' );

//var_dump( $image->getImageInfo() );
...全文
612 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
PleaseDoTellMeWhy 2006-09-30
  • 打赏
  • 举报
回复
jf
an9ryfr09 2006-09-30
  • 打赏
  • 举报
回复
想支持中文很简单,将编码转换为utf-8就可以了,可以使用iconv函数但是必须保证你的php环境支持。

想要做成验证码必须加入干扰象素。更多的功能希望大家一起扩展
wuwwq 2006-09-30
  • 打赏
  • 举报
回复
要是不支持中文我想不可以用吧。
an9ryfr09 2006-09-30
  • 打赏
  • 举报
回复
加一个函数,使其支持汉字

function setCharset( $from_charset,$to_charset ){
$this->mImages->context = iconv( $from_charset, $to_charset , $this->mImages->context );
}

调用时$image->setCharset( 'gb2312','UTF-8');一下,就可以传汉字编码了。
iasky 2006-09-29
  • 打赏
  • 举报
回复
jf

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧