php生成文字水印,并將圖片另存,下面是代碼,修改了多次,可以防止中文亂碼,但是要求字體,根據(jù)下面的提示進(jìn)行配置,這樣php文字水印很容易就輸出了。
//參數(shù)分別是 原始圖片 保存圖片 位置 文字水印內(nèi)容 水印數(shù)量 文字水印顏色 文字水印字體
//字體在當(dāng)前文件夾下
function imageWaterMark($groundImage,$savename,$pos=0,$waterText="",$number=1,$textColor="#cccccc",$font = "simhei.ttf")
{
$formatMsg = "僅僅能為GIF、JPG、PNG添加水印圖片";
if($savename=="")$savename = $groundImage;
$font = dirname(__FILE__)."\\".$font;
$font = str_replace("\\","/",$font);
if(!empty($font) && !file_exists($font)){
die("font not exists");
}
if(!empty($groundImage) && file_exists($groundImage))
{
$ground_info = getimagesize($groundImage);
$ground_w = $ground_info[0];//取得背景圖片的寬
$ground_h = $ground_info[1];//取得背景圖片的高
switch($ground_info[2])//取得背景圖片的格式
{
case 1:$ground_im = imagecreatefromgif($groundImage);break;
case 2:$ground_im = imagecreatefromjpeg($groundImage);break;
case 3:$ground_im = imagecreatefrompng($groundImage);break;
default:die($formatMsg);
}
}else{
die("需要加文字水印的圖片不存在!");
}
$w = $h = 0 ;//這里是文字水印的的寬度和高度,無法定義
for($number;$number>1;$number--){
switch($pos)
{
case 0://隨機
$posX = rand(50,($ground_w - $w ));
$posY = rand(120,($ground_h - $h ));
break;
case 1://文字水印頂端居左
$posX = 0;
$posY = 0;
break;
case 2://文字水印頂端居中
$posX = ($ground_w - $w) / 2;
$posY = 0;
break;
case 3://文字水印頂端居右
$posX = $ground_w - $w;
$posY = 0;
break;
case 4://文字水印中部居左
$posX = 0;
$posY = ($ground_h - $h) / 2;
break;
case 5://文字水印中部居中
$posX = ($ground_w - $w) / 2;
$posY = ($ground_h - $h) / 2;
break;
case 6://文字水印中部居右
$posX = $ground_w - $w;
$posY = ($ground_h - $h) / 2;
break;
case 7://文字水印底端居左
$posX = 0;
$posY = $ground_h - $h;
break;
case 8://文字水印底端居中
$posX = ($ground_w - $w) / 2;
$posY = $ground_h - $h;
break;
case 9://文字水印為底端居右
$posX = $ground_w - $w;
$posY = $ground_h - $h;
break;
case 11:
$posX = $ground_w - $w;
$posY = $ground_h - $h;
break;
default://文字水印隨機
$posX = rand(0,($ground_w - $w));
$posY = rand(0,($ground_h - $h));
break;
}
//設(shè)定文字水印圖片顏色圖像的混色模式
imagealphablending($ground_im, true);
if( !empty($textColor) && (strlen($textColor)==7) ){
$R = hexdec(substr($textColor,1,2));
$G = hexdec(substr($textColor,3,2));
$B = hexdec(substr($textColor,5));
}else{
die("水印文字顏色格式不正確!");
}
imagettftext($ground_im, 20, 0, $posX, $posY, imagecolorallocate($ground_im, $R, $G, $B), $font, $waterText);//將文字寫到圖片中 img size angle beginx beginy color fonttype content
}
switch($ground_info[2])//取得背景圖片的格式 ,并保存文字水印圖片
{
case 1:imagegif($ground_im,$savename);break;
case 2:imagejpeg($ground_im,$savename);break;
case 3:imagepng($ground_im,$savename);break;
default:die($errorMsg);
}
//釋放內(nèi)存
unset($ground_info);
imagedestroy($ground_im);
}
上面就是php 生成文字水印圖片函數(shù),如果使用拿去吧。
更多信息請查看IT技術(shù)專欄
2025國考·省考課程試聽報名