PHP修改圖片

ndblog發表於2014-05-15

這篇是關於修改圖片的效果,主要還是用到php中的GD庫中的函式,沒想到php還有這凶殘能力,出乎我的預料。

先看程式碼upload_image.php,主要是一個上傳控制元件,用來選擇圖片

<html>
    <head>
        <title></title>
        <style type="text/css"></style>
    </head>
    <body>
        <form action="check_image.php" method="post" enctype="multipart/form-data">
            <table>
                <tr>
                    <td>Your username</td>
                    <td><input type="text" name="username" /></td>
                </tr>
                <tr>
                    <td>Upload image*</td>
                    <td><input type="file" name="uploadfile"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <small><em> * Acceptable image formats include: GIF, JPG/JPEG and PNG.</em></small>
                    </td>
                </tr>
                <tr>
                    <td>Image Caption</td>
                    <td><input type="text" name="caption"/></td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align:center;">
                        <input type="submit" name="submit" value="Upload" />
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

然後是上傳和處理圖片的邏輯check_image.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:Seriousphpdev	estimages`;

//upload_image.php頁面傳遞過來的引數,如果是上傳圖片
if($_POST[`submit`] == `Upload`)
{
    if($_FILES[`uploadfile`][`error`] != UPLOAD_ERR_OK)
    {
        switch($_FILES[`uploadfiel`][`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;    
    }
    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`];
        }
    ?>
    <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;?>"/>
            <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 />
            <input type="submit" value="Preview" name="submit" /><br />
            <input type="submit" value="Save" name="submit" />
            
        </div>
    </form>
<?php 
}
?>

最後是一個預覽效果的頁面image_effect.php

<?php 
$dir = `D:Seriousphpdev	estimages`;

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;    
}
header(`Content-Type:image/jpeg`);
imagejpeg($image , `` , 100);

?>

第二個image_check.php有點亂,在這個頁面中有上傳圖片,處理圖片,還有預覽圖片的部分邏輯,注意下面這段

    <?php
        if($_POST[`submit`] == `Upload`)
        {
            $imagename = `images/`.$image_id.`.jpg`;
        }
        else
        {
            $imagename = `image_effect.php?id=`.$image_id.`&e=`.$_POST[`effect`];
        }
    ?>
    <img src="<?php echo $imagename;?>" style="float:left;" alt="" />

如果是上傳直接訪問圖片,如果是預覽則從image_effect.php中讀取圖片,這裡是從記憶體中讀取圖片並根據選擇的處理效果來展示圖片。如下

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;    
}

當使用imagefilter方法處理圖片之後會把圖片輸出到頁面,這裡要注意imagejpeg方法的第二個引數是空字串,這樣它就不會寫入到硬碟中了,如果第二個引數設定了會覆蓋原有的圖片,這樣可以讓使用者在儲存圖片之前隨意的預覽效果,如下:

header(`Content-Type:image/jpeg`);
imagejpeg($image , `` , 100);

在check_image.php中有呼叫到類似的方法,但是這裡指定了第二個引數,就是用來儲存圖片的:

imagejpeg($image , $dir.`/`.$_POST[`id`].`.jpg` , 100);

注意這裡哦我們只寫了三種處理效果,這個只是所有列舉中的一部分,我們來看所有的處理方式:

IMG_FILTER_NEGATE:將影像中所有顏色反轉。
IMG_FILTER_GRAYSCALE:將影像轉換為灰度的。
IMG_FILTER_BRIGHTNESS:改變影像的亮度。用 arg1 設定亮度級別。
IMG_FILTER_CONTRAST:改變影像的對比度。用 arg1 設定對比度級別。
IMG_FILTER_COLORIZE:與 IMG_FILTER_GRAYSCALE 類似,不過可以指定顏色。用 arg1,arg2 和 arg3 分別指定 red,blue 和 green。每種顏色範圍是 0 到 255。
IMG_FILTER_EDGEDETECT:用邊緣檢測來突出影像的邊緣。
IMG_FILTER_EMBOSS:使影像浮雕化。
IMG_FILTER_GAUSSIAN_BLUR:用高斯演算法模糊影像。
IMG_FILTER_SELECTIVE_BLUR:模糊影像。
IMG_FILTER_MEAN_REMOVAL:用平均移除法來達到輪廓效果。
IMG_FILTER_SMOOTH:使影像更柔滑。用 arg1 設定柔滑級別。

是不是很驚豔,php很強大的。

 

作者:Tyler Ning

出處:http://www.cnblogs.com/tylerdonet/

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,如有問題,可以通過以下郵箱地址williamningdong@gmail.com
 聯絡我,非常感謝。


相關文章