<?php $bg_src="./bg.jpg"; $logo_src="./logo.png"; //獲取圖片的width寬、height高、mime後綴類型 $bg_size=getimagesize($bg_src); $logo_size=getimagesize($logo_src); $bg_width=$bg_size[0]; $bg_height=$bg_size[1]; $bg_mime=$bg_size['mime']; $logo_width=$logo_size[0]; $logo_height=$logo_size[1]; $logo_mime=$logo_size['mime']; $position=0;//水印相對背景圖的位置;0表示位置在左上角,1表示位置在上邊中間,2表示位置在右上角,3表示位置在左側中間,4表示位置在中心,5表示位置在右側中間,6表示位置在左下角,7表示位置在下邊中間,8表示位置在右下角 $alpha=100;//水印的透明度0~100 //1.打開兩張圖片 function openimage($mime,$src){ switch ($mime){ case "image/jpeg": $img=imagecreatefromjpeg($src); break; case "image/png": $img=imagecreatefrompng($src); break; case "image/gif": $img=imagecreatefromgif($src); break; case "image/wbmp": $img=imagecreatefromwbmp($src); break; case "image/xbm": $img=imagecreatefromxbm($src); break; } return $img; } $bg=openimage($bg_mime,$bg_src); $logo=openimage($logo_mime,$logo_src); //2.合併兩張圖片 switch ($position){ case 0: $x=0; $y=0; break; case 1: $x=$bg_width/2-$logo_width/2; $y=0; break; case 2: $x=$bg_width-$logo_width; $y=0; break; case 3: $x=0; $y=$bg_height/2-$logo_height/2; break; case 4: $x=$bg_width/2-$logo_width/2; $y=$bg_height/2-$logo_height/2; break; case 5: $x=$bg_width-$logo_width; $y=$bg_height/2-$logo_height/2; break; case 6: $x=0; $y=$bg_height-$logo_height; break; case 7: $x=bg_width/2-$logo_width/2; $y=$bg_height-$logo_height; break; case 8: $x=$bg_width-$logo_width; $y=$bg_height-$logo_height; break; } imagecopymerge($bg,$logo,$x,$y,0,0,$logo_width,$logo_height,$alpha); //3.通知瀏覽器以圖像形式展示 header("content-type:image/png"); //4.輸出圖像 imagepng($bg); //5.釋放資源 imagedestroy($bg); imagedestroy($logo); ?>
若要將添加水印後的圖片保存下來而非僅顯示在瀏覽器中,則須在「4.輸出圖像」的步驟中使用imagepng()一類函數的另外一形式:imagepng($bg,'生成圖片的路徑名稱.後綴');php
//3.通知瀏覽器以圖像形式展示,若僅需保存無需在瀏覽器顯示則註釋這句 header("content-type:image/png"); //4.輸出圖像 imagepng($bg); //若僅需保存無需在瀏覽器顯示則註釋這句 //若要保存圖像: //獲取底板圖片的文件擴展名 $ext=pathinfo($bg_src)['extension']; //生成一個隨機且惟一性的文件名 $filename=md5(uniqid(microtime(true),true)).".".$ext; //設置要輸出的文件路徑 $filepath="./".$filename; switch ($ext) { case 'jpg': case 'jpeg': case 'jpe': imagejpeg($bg,$filepath); break; case 'png': imagepng($bg,$filepath); break; case 'gif': imagegif($bg,$filepath); break; case 'bmp': case 'wbmp': imagewbmp($bg,$filepath); break; case 'xbm': imagexbm($bg,$filepath); break; }