1: 面向過程的編寫方法
//指定圖片路徑
$src = '001.png';
//獲取圖片信息
$info = getimagesize($src);
//獲取圖片擴展名
$type = image_type_to_extension($info[2],false);
//動態的把圖片導入內存中
$fun = "imagecreatefrom{$type}";
$image = $fun('001.png');
//指定字體顏色
$col = imagecolorallocatealpha($image,255,255,255,50);
//指定字體內容
$content = 'helloworld';
//給圖片添加文字
imagestring($image,5,20,30,$content,$col);
//指定輸入類型
header('Content-type:'.$info['mime']);
//動態的輸出圖片到浏覽器中
$func = "image{$type}";
$func($image);
//銷毀圖片
imagedestroy($image);
2:面向對象的實現方法
class Image_class {
private $image;
private $info;
/**
* @param $src:圖片路徑
* 加載圖片到內存中
*/
function __construct($src){
$info = getimagesize($src);
$type = image_type_to_extension($info[2],false);
$this -> info =$info;
$this->info['type'] = $type;
$fun = "imagecreatefrom" .$type;
$this -> image = $fun($src);
}
/**
* @param $fontsize: 字體大小
* @param $x: 字體在圖片中的x位置
* @param $y: 字體在圖片中的y位置
* @param $color: 字體的顏色是一個包含rgba的數組
* @param $text: 想要添加的內容
* 操作內存中的圖片,給圖片添加文字水印
*/
public function fontMark($fontsize,$x,$y,$color,$text){
$col = imagecolorallocatealpha($this->image,$color[0],$color[1],$color[2],$color[3]);
imagestring($this->image,$fontsize,$x,$y,$text,$col);
}
/*
* 輸出圖片到浏覽器中
*/
public function show(){
header('content-type:' . $this -> info['mime']);
$fun='image' . $this->info['type'];
$fun($this->image);
}
/**
* 銷毀圖片
*/
function __destruct(){
imagedestroy($this->image);
}
}
//對類的調用
$obj = new Image_class('001.png');
$obj->fontMark(20,20,30,array(255,255,255,60),'hello');
$obj->show();