php給圖片加水印


這一篇我們來看看那如何給圖片添加水印,其實是把原圖片和水印圖片合並在一起。

先看文件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';
//設置環境變量
putenv('GDFONTPATH='.'C:\Windows\Fonts');
$font = "arial";

//upload_image.php頁面傳遞過來的參數,如果是上傳圖片
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  //如果圖片已經上傳,則從數據庫中取圖片名字
{
    $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);     //將圖像中所有顏色反轉
        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($_POST['emb_caption']))
    {
        imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption);
    }
    if(isset($_POST['emb_logo']))
    {
        //獲取水印圖片的尺寸並創建水印
        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 />';
                //添加水印選項
                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 
}
?>

這里面主要是添加水印選項,如果選中添加水印則將logo.png作為水印圖片和原來的圖片合並在一起。

在預覽文件中添加了對應的邏輯,代碼如下:

<?php 
$dir = 'D:\Serious\phpdev\test\images';
//設置環境變量
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() 方法把兩個圖片合並在一起造成水印效果。來看看這個方法的方法原型和參數:

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 圖像中坐標從 src_x,src_y 開始,寬度為 src_w,高度為 src_h 的一部分拷貝到 dst_im 圖像中坐標為 dst_x 和 dst_y 的位置上。兩圖像將根據 pct 來決定合並程度,其值范圍從 0 到 100。當 pct = 0 時,實際上什么也沒做,當為 100 時對於調色板圖像本函數和 imagecopy() 完全一樣,它對真彩色圖像實現了 alpha 透明。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM