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: 想要添加的內容 * 操作記憶體中的圖片,給圖片添加文字浮水印 */publicfunction 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); } /* * 輸出圖片到瀏覽器中 */publicfunction 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();
以上就介紹了利用php給圖片添加文字浮水印--物件導向與面向過程倆種方法的實現,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。