PHP添加圖片水印、壓縮、剪切的封裝類
給圖片添加水印,其實(shí)就是把原來的圖片和水印添加在一起,下面小編把最近整理的資料分享給大家。
php對圖片文件的操作主要是利用GD庫擴(kuò)展。當(dāng)我們頻繁利用php對圖片進(jìn)行操作時(shí),會(huì)自然封裝很多函數(shù),否則會(huì)寫太多重復(fù)的代碼。當(dāng)有很多對圖片的相關(guān)函數(shù)的時(shí)候,我們可以考慮將這些函數(shù)也整理一下,因而就有了封裝成類的想法。
操作圖片主要?dú)v經(jīng)四個(gè)步驟:
第一步:打開圖片
第二步:操作圖片
第三步:輸出圖片
第四步:銷毀圖片
1,3,4三個(gè)步驟每次都要寫,每次又都差不多。真正需要變通的只有操作圖片的這一步驟了。操作圖片又往往通過1或多個(gè)主要的GD函數(shù)來完成。
本文封裝類里面的四種方法,文字水?。╥magettftext()),圖片水?。╥magecopymerge()),圖片壓縮,圖片剪切(imagecopyresampled()),其余的常用GD函數(shù)便不贅述。
直接上代碼:
<?php class Image { private $info; private $image; public $type; public function __construct($src) { $this->info=getimagesize($src); $this->type=image_type_to_extension($this->info['2'],false); $fun="imagecreatefrom{$this->type}"; $this->image=$fun($src); } /** * 文字水印 * @param [type] $font 字體 * @param [type] $content 內(nèi)容 * @param [type] $size 文字大小 * @param [type] $col 文字顏色(四元數(shù)組) * @param array $location 位置 * @param integer $angle 傾斜角度 * @return [type] */ public function fontMark($font,$content,$size,$col,$location,$angle=0){ $col=imagecolorallocatealpha($this->image, $col['0'], $col['1'], $col['2'],$col['3']); imagettftext($this->image, $size, $angle, $location['0'], $location['1'], $col,$font,$content); } /** * 圖片水印 * @param [type] $imageMark 水印圖片地址 * @param [type] $dst 水印圖片在原圖片中的位置 * @param [type] $pct 透明度 * @return [type] */ public function imageMark($imageMark,$dst,$pct){ $info2=getimagesize($imageMark); $type=image_type_to_extension($info2['2'],false); $func2="imagecreatefrom".$type; $water=$func2($imageMark); imagecopymerge($this->image, $water, $dst[0], $dst[1], 0, 0, $info2['0'], $info2['1'], $pct); imagedestroy($water); } /** * 壓縮圖片 * @param [type] $thumbSize 壓縮圖片大小 * @return [type] [description] */ public function thumb($thumbSize){ $imageThumb=imagecreatetruecolor($thumbSize[0], $thumbSize[1]); imagecopyresampled($imageThumb, $this->image, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $this->info['0'], $this->info['1']); imagedestroy($this->image); $this->image=$imageThumb; } /** * 裁剪圖片 * @param [type] $cutSize 裁剪大小 * @param [type] $location 裁剪位置 * @return [type] [description] */ public function cut($cutSize,$location){ $imageCut=imagecreatetruecolor($cutSize[0],$cutSize[1]); imagecopyresampled($imageCut, $this->image, 0, 0, $location[0], $location[1],$cutSize[0],$cutSize[1],$cutSize[0],$cutSize[1]); imagedestroy($this->image); $this->image=$imageCut; } /** * 展現(xiàn)圖片 * @return [type] [description] */ public function show(){ header("content-type:".$this->info['mime']); $funn="image".$this->type; $funn($this->image); } /** * 保存圖片 * @param [type] $newname 新圖片名 * @return [type] [description] */ public function save($newname){ header("content-type:".$this->info['mime']); $funn="image".$this->type; $funn($this->image,$newname.'.'.$this->type); } public function __destruct(){ imagedestroy($this->image); } } ?>
如果還需要其他操作,只需要再往這個(gè)類里面添加就好啦~~
給圖片添加水印代碼:
先看文件check_image_addwatermark.php代碼
<?php //修改圖片效果 $db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database'); mysql_select_db('moviesite',$db) or die(mysql_error($db)); //上傳文件的路徑 $dir = 'D:\Serious\phpdev\test\images'; //設(shè)置環(huán)境變量 putenv('GDFONTPATH='.'C:\Windows\Fonts'); $font = "arial"; //upload_image.php頁面?zhèn)鬟f過來的參數(shù),如果是上傳圖片 if($_POST['submit'] == 'Upload') { if($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK) { switch($_FILES['uploadfile']['error']) { case UPLOAD_ERR_INI_SIZE: die('The uploaded file exceeds the upload_max_filesize directive'); break; case UPLOAD_ERR_FORM_SIZE: die('The upload file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'); break; case UPLOAD_ERR_PARTIAL: die('The uploaded file was only partially uploaded'); break; case UPLOAD_ERR_NO_FILE: die('No file was uploaded'); break; case UPLOAD_ERR_NO_TMP_DIR: die('The server is missing a temporary folder'); break; case UPLOAD_ERR_CANT_WRITE: die('The server fail to write the uploaded file to the disk'); break; case UPLOAD_ERR_EXTENSION: die('The upload stopped by extension'); break; } } $image_caption = $_POST['caption']; $image_username = $_POST['username']; $image_date = date('Y-m-d'); list($width,$height,$type,$attr) = getimagesize($_FILES['uploadfile']['tmp_name']); $error = 'The file you upload is not a supported filetype'; switch($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error); break; default: break; } $query = 'insert into images(image_caption,image_username,image_date) values("'.$image_caption.'" , "'.$image_username.'","'.$image_date.'")'; $result = mysql_query($query,$db) or die(mysql_error($db)); $last_id = mysql_insert_id(); // $imagename = $last_id.'.jpg'; // imagejpeg($image,$dir.'/'.$imagename); // imagedestroy($image); $image_id = $last_id; imagejpeg($image , $dir.'/'.$image_id.'.jpg'); imagedestroy($image); } else //如果圖片已經(jīng)上傳,則從數(shù)據(jù)庫中取圖片名字 { $query = 'select image_id,image_caption,image_username,image_date from images where image_id='.$_POST['id']; $result = mysql_query($query,$db) or die(mysql_error($db)); extract(mysql_fetch_assoc($result)); list($width,$height,$type,$attr) = getimagesize($dir.'/'.$image_id.'.jpg'); } //如果是保存圖片 if($_POST['submit'] == 'Save') { if(isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir.'/'.$_POST['id'].'.jpg')) { $image = imagecreatefromjpeg($dir.'/'.$_POST['id'].'.jpg'); } else { die('invalid image specified'); } $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1; switch($effect) { case IMG_FILTER_NEGATE: imagefilter($image , IMG_FILTER_NEGATE); //將圖像中所有顏色反轉(zhuǎn) break; case IMG_FILTER_GRAYSCALE: imagefilter($image , IMG_FILTER_GRAYSCALE); //將圖像轉(zhuǎn)換為灰度的 break; case IMG_FILTER_EMBOSS: imagefilter($image , IMG_FILTER_EMBOSS); //使圖像浮雕化 break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR); //用高斯算法模糊圖像 break; } if(isset($_POST['emb_caption'])) { imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption); } if(isset($_POST['emb_logo'])) { //獲取水印圖片的尺寸并創(chuàng)建水印 list($wmk_width , $wmk_height) = getimagesize('images/logo.png'); $x = ($width-$wmk_width) / 2; $y = ($height-$wmk_height)/2; $wmk = imagecreatefrompng('images/logo.png'); //把水印圖片和原圖片合并在一起 imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20); //清除水印圖片 imagedestroy($wmk); } imagejpeg($image , $dir.'/'.$_POST['id'].'.jpg' , 100); ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>Your image has been saved!</h1> <img src="images/<?php echo $_POST['id'];?>.jpg" alt="" /> </body> </html> <?php } else { ?> <html> <head> <title>Here is your pic!</title> </head> <body> <h1>So how does it feel to be famous?</h1> <p>Here is the picture you just uploaded to your servers:</p> <!--<img src="images/<?php echo $imagename;?>" alt="" style="float:left;" />--> </body> </html> <?php if($_POST['submit'] == 'Upload') { $imagename = 'images/'.$image_id.'.jpg'; } else { $imagename = 'image_effect.php?id='.$image_id.'&e='.$_POST['effect']; if(isset($_POST['emb_caption'])) { $imagename .= '&capt='.urlencode($image_caption); } if(isset($_POST['emb_logo'])) { $imagename .= '&logo=1'; } } ?> <img src="<?php echo $imagename;?>" style="float:left;" alt="" /> <table> <tr> <td>Image save as:</td> <td><?php $image_id?></td> </tr> <tr> <td>Height:</td> <td><?php echo $height;?></td> </tr> <tr> <td>Widht:</td> <td><?php echo $width;?></td> </tr> <tr> <td>Upload date:</td> <td><?php echo $image_date;?></td> </tr> </table> <p>You may apply a special effect to your image from the list of option below. Note:saving an image with any of the filters applied <em>can be undone</em> </p> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <div> <input type="hidden" name="id" value="<?php echo $image_id;?>"/> Filter:<select name="effect" id=""> <option value="-1">None</option> <?php echo '<option value="'.IMG_FILTER_GRAYSCALE.'" '; if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE) { echo 'selected="selected"'; } echo ' >Black and white</option>'; echo '<option value="'.IMG_FILTER_GAUSSIAN_BLUR.'"'; if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR) { echo ' selected="selected"'; } echo '>Blur</option>'; echo '<option value="'.IMG_FILTER_EMBOSS.'"'; if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS) { echo 'selected="selected"'; } echo '>Emboss</option>'; echo '<option value="'.IMG_FILTER_NEGATE.'"'; if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE) { echo 'selected="selected"'; } echo '>Negative</option>'; ?> </select><br /> <?php echo '<input type="checkbox" name="emb_caption"'; if(isset($_POST['emb_caption'])) { echo ' checked="checked"'; } echo ' />Embed caption in image?'; echo '<br />'; //添加水印選項(xiàng) echo '<input type="checkbox" name="emb_logo" '; if(isset($_POST['emb_logo'])) { echo 'checked="checked"'; } echo ' />Embed watermarked logo in image?'; ?> <input type="submit" value="Preview" name="submit" /><br /><br /> <input type="submit" value="Save" name="submit" /> </div> </form> <?php } ?>
這里面主要是添加水印選項(xiàng),如果選中添加水印則將logo.png作為水印圖片和原來的圖片合并在一起。
在預(yù)覽文件中添加了對應(yīng)的邏輯,代碼如下:
<?php $dir = 'D:\Serious\phpdev\test\images'; //設(shè)置環(huán)境變量 putenv('GDFONTPATH='.'C:\Windows\Fonts'); $font = "arial"; if(isset($_GET['id']) && ctype_digit($_GET['id']) && file_exists($dir.'/'.$_GET['id'].'.jpg')) { $image = imagecreatefromjpeg($dir.'/'.$_GET['id'].'.jpg'); } else { die('invalid image specified'); } $effect = (isset($_GET['e'])) ? $_GET['e'] : -1; switch($effect) { case IMG_FILTER_NEGATE: imagefilter($image , IMG_FILTER_NEGATE); break; case IMG_FILTER_GRAYSCALE: imagefilter($image , IMG_FILTER_GRAYSCALE); break; case IMG_FILTER_EMBOSS: imagefilter($image , IMG_FILTER_EMBOSS); break; case IMG_FILTER_GAUSSIAN_BLUR: imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR); break; } if(isset($_GET['capt'])) { //echo $_GET['capt']; imagettftext($image, 12, 0, 20, 20, 0, $font, $_GET['capt']); } if(isset($_GET['logo'])) { list($widht , $height) = getimagesize($dir.'/'.$_GET['id'].'.jpg'); list($wmk_width , $wmk_height) = getimagesize('images/logo.png'); $x = ($widht-$wmk_width) / 2; $y = ($height-$wmk_height) / 2; $wmk = imagecreatefrompng('images/logo.png'); imagecopymerge($image , $wmk , $x , $y , 0 , 0 , $wmk_width , $wmk_height , 20); imagedestroy($wmk); } header('Content-Type:image/jpeg'); imagejpeg($image , '' , 100); ?>
最后上傳的水印圖片效果如下:
注意主要的邏輯就是通過 imagecopymerge() 方法把兩個(gè)圖片合并在一起造成水印效果。來看看這個(gè)方法的方法原型和參數(shù):
bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int$src_x , int $src_y , int $src_w , int $src_h , int $pct )
將 src_im 圖像中坐標(biāo)從 src_x,src_y 開始,寬度為 src_w,高度為 src_h 的一部分拷貝到 dst_im 圖像中坐標(biāo)為 dst_x 和 dst_y 的位置上。兩圖像將根據(jù) pct 來決定合并程度,其值范圍從 0 到 100。當(dāng) pct = 0 時(shí),實(shí)際上什么也沒做,當(dāng)為 100 時(shí)對于調(diào)色板圖像本函數(shù)和 imagecopy() 完全一樣,它對真彩色圖像實(shí)現(xiàn)了 alpha 透明。
以上內(nèi)容是本文介紹PHP給圖片添加水印 壓縮 剪切的封裝類的全部內(nèi)容,希望大家對本文介紹感興趣。
- PHP圖像處理技術(shù)實(shí)例總結(jié)【繪圖、水印、驗(yàn)證碼、圖像壓縮】
- PHP圖片裁剪函數(shù)(保持圖像不變形)
- PHP圖像識別技術(shù)原理與實(shí)現(xiàn)
- PHP中繪制圖像的一些函數(shù)總結(jié)
- php圖像處理函數(shù)大全(推薦收藏)
- php使用imagick模塊實(shí)現(xiàn)圖片縮放、裁剪、壓縮示例
- 基于PHP實(shí)現(xiàn)等比壓縮圖片大小
- 淺談關(guān)于PHP解決圖片無損壓縮的問題
- php高清晰度無損圖片壓縮功能的實(shí)現(xiàn)代碼
- PHP的圖像處理實(shí)例小結(jié)【文字水印、圖片水印、壓縮圖像等】
相關(guān)文章
php的mkdir()函數(shù)創(chuàng)建文件夾比較安全的權(quán)限設(shè)置方法
這篇文章主要介紹了php的mkdir()函數(shù)創(chuàng)建文件夾比較安全的權(quán)限設(shè)置方法,遇到的情況是系統(tǒng)umask影響了mkdir的指定權(quán)限參數(shù)比期望要小,使用chmod函數(shù)則沒有這個(gè)問題,需要的朋友可以參考下2014-07-07PHP+fiddler抓包采集微信文章閱讀數(shù)點(diǎn)贊數(shù)的思路詳解
這篇文章主要介紹了PHP+fiddler抓包采集微信文章閱讀數(shù)點(diǎn)贊數(shù)的思路,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12laravel5.0在linux下解決.htaccess無效和去除index.php的問題
今天小編就為大家分享一篇laravel5.0在linux下解決.htaccess無效和去除index.php的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10Ajax PHP JavaScript MySQL實(shí)現(xiàn)簡易無刷新在線聊天室
這篇文章主要為大家詳細(xì)介紹了Ajax PHP JavaScript MySQL實(shí)現(xiàn)簡易無刷新在線聊天室,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-08-08codeigniter框架The URI you submitted has disallowed characters
這篇文章主要介紹了codeigniter框架The URI you submitted has disallowed characters錯(cuò)誤解決方法,需要的朋友可以參考下2014-05-05以實(shí)例全面講解PHP中多進(jìn)程編程的相關(guān)函數(shù)的使用
這篇文章主要介紹了以實(shí)例全面講解PHP中多進(jìn)程編程的相關(guān)函數(shù)的使用,包括對僵尸進(jìn)程的處理等方面,極力推薦!需要的朋友可以參考下2015-08-08