1. 程式人生 > 其它 >php 圖片旋轉新增水印

php 圖片旋轉新增水印

 /*
     * 生成水印logo
     * text 水印文字 bigImgPath 背景圖
     */
    public static function make_watermark_img($text, $bigImgPath)
    {
        if (strtoupper(substr(PHP_OS,0,3))==='WIN')
        {
            $font = "c:/windows/fonts/SIMHEI.TTF";//字型型別,這裡為黑體,
        }else{
            $font = "/usr/share/fonts/simhei.ttf";//
字型型別,這裡為黑體, } $text_len = strlen($text) / 3; //顯示的文字 $width = $text_len * 17; //1個字17 $logo = 'uploads/'.$text.'.png'; //水印文字圖片地址 $size = 12; //字型大小 $img = imagecreate($width,24);//建立一個長為x高為y的空白圖片 imagecolorallocate($img,0xff,0xff,0xff);//設定圖片背景顏色,這裡背景顏色為#ffffff,也就是白色
$black=imagecolorallocate($img,0x00,0x00,0x00);//設定字型顏色,這裡為#000000,也就是黑色 imagettftext($img,$size,0,0,16, $black, $font , $text);//將ttf文字寫到圖片中 $watermark_logo = imagepng($img, $logo);//輸出圖片,輸出png使用imagepng方法,輸出gif使用imagegif方法 if (!$watermark_logo) { return ['status'=>false, 'msg' => '生成水印失敗']; }
//圖片旋轉 self::flip($logo, $logo, 45); //新增水印 $a = self::add_watermark($logo, $bigImgPath); print_r($a);die; } /* * 新增水印 */ public static function add_watermark($logo, $bigImgPath) { $im = imagecreatefromstring(file_get_contents($bigImgPath)); //獲取水印源 $watermark = imagecreatefromstring(file_get_contents($logo)); //獲取圖、水印 寬高型別 list($bgWidth, $bgHight, $bgType) = getimagesize($bigImgPath); list($logoWidth, $logoHight, $logoType) = getimagesize($logo); //定義平鋪資料 $x_length = $bgWidth - 10; //x軸總長度 $y_length = $bgHight - 10; //y軸總長度 //建立透明畫布 偽白色 $opacity = 30; $w = imagesx($watermark); $h = imagesy($watermark); $cut = imagecreatetruecolor($w,$h); $white = imagecolorallocatealpha($cut, 255,255,255,0); imagefill( $cut, 0, 0, $white ); //整合水印 imagecopy($cut, $watermark, 0, 0, 0, 0, $w, $h); //迴圈平鋪水印 for ($x = 0; $x < $x_length; $x++) { for ($y = 0; $y < $y_length; $y++) { imagecopymerge($im, $cut, $x, $y, 0, 0, $logoWidth, $logoHight, $opacity); $y += $logoHight; } $x += $logoWidth; } header("Content-type:image/png"); // imagejpeg 的第二個引數不傳, 預設是顯示圖片 $keys = array_merge(range(0, 9), range('a', 'z')); $key = ''; for ($i = 0; $i < 15; $i++) { $key .= $keys[array_rand($keys)]; } $fileName = $key.time().'.png'; $file_path = 'uploads/'.$fileName; $img = imagepng($im); print_r($img);die; } /** * @param $filename // 圖片原始地址 * @param $src // 旋轉後圖片儲存地址 * @param int $degrees // 旋轉角度 * @return bool */ public static function flip($filename,$src,$degrees = 45) { //讀取圖片 $data = @getimagesize($filename); if($data==false)return false; //讀取舊圖片 switch ($data[2]) { case 1: $src_f = imagecreatefromgif($filename);break; case 2: $src_f = imagecreatefromjpeg($filename);break; case 3: $src_f = imagecreatefrompng($filename);break; } if($src_f=="")return false; $rotate = @imagerotate($src_f, $degrees,0); if(!imagejpeg($rotate,$src,100))return false; @imagedestroy($rotate); return true; }