PHP-生成縮略圖和添加水印圖-學習筆記

来源:http://www.cnblogs.com/wghao/archive/2017/01/07/6258756.html
-Advertisement-
Play Games

寫了一個圖片處理的Image類,1.能生成縮略圖,不失真,不出現黑邊;2.添加水印圖,能根據圖片大小,自動縮放水印圖。 ...


1.開始

    在網站上傳圖片過程,經常用到縮略圖功能。這裡我自己寫了一個圖片處理的Image類,能生成縮略圖,並且可以添加水印圖。

 

2.如何生成縮略圖

     生成縮略圖,關鍵的是如何計算縮放比率。

     這裡,我根據圖片等比縮放,寬高的幾種常見變化,得出一個算縮放比率演算法是,使用新圖(即縮略圖)的寬高,分別除以原圖的寬高,看哪個值大,就取它作為縮放比率:

               縮放比率  = Max( { 新圖高度  / 原圖高度 新圖寬度  / 原圖寬度 } )

     也就是:

      If ( (新圖高度  / 原圖高度)  >  (新圖寬度  / 原圖寬度 ) )  {

              縮放比率 新圖高度  / 原圖高度

      }ELSE {

             縮放比率 新圖寬度 / 原圖寬度;

     }

 這裡列出場景的圖片縮放場景,及處理方法: 

 e.g 

場景1原圖比新圖大的情況, 縮放比率 =  新圖寬度 / 原圖寬度 :

場景2,原圖比新圖大的情況,b. 縮放比率 =  新圖高度 / 原圖高度 :

場景3,原圖比新圖大的情況,而且新圖寬高相等,即新圖形狀是正方形,那麼上面的縮放演算法也是適用的。

場景4,如果 “新圖寬度 >= 原圖寬度”  ,同時  “新圖高度 >= 原圖高度”,那麼不縮放圖片,也不放大圖片,保持原圖。

場景5,如果 “新圖寬度 < 原圖寬度”,同時  “新圖高度 >= 原圖高度”  ,那麼先設置  “新圖高度= 原圖高度”,再剪切。

場景6,如果 “新圖高度 < 原圖高度”,同時  “新圖寬度 >= 原圖寬度”  ,那麼先設置  “新圖寬度= 原圖寬度”,再剪切。

3.如何添加水印圖片

   添加水印很容易,我這裡沒考慮那麼複雜,主要是控制水印位置在圖片的右下角,和控制水印在圖片中的大小。如,當目標圖片與水印圖大小接近,那麼需要先等比縮放水印圖片,再添加水印圖片。

左邊兩幅圖,上面是原圖,下麵是水印圖,右邊的縮放後加水印的新圖。

 

4.類圖

5.PHP代碼

     5.1. 構造函數 __construct()

     在Image類中,除了構造函數__construct()是public,其它函數都為private.也就是在函數__construct()中,直接完成了生成縮略圖和添加水印圖的功能。如果,只生成縮略圖而不需要添加水印,那麼直接在__construct()的參數$markPath,設置為null即可。

     其中,“$this->quality = $quality ? $quality : 75;” 控制輸出為JPG圖片時,控製圖片質量(0-100),預設值為75;

     /**
     * Image constructor.
     * @param string $imagePath 圖片路徑
     * @param string $markPath 水印圖片路徑
     * @param int $new_width 縮略圖寬度
     * @param int $new_height 縮略圖高度
     * @param int $quality JPG圖片格輸出質量
     */
    public function __construct(string $imagePath,
                                string $markPath = null,
                                int $new_width = null,
                                int $new_height = null,
                                int $quality = 75)
    {
        $this->imgPath = $_SERVER['DOCUMENT_ROOT'] . $imagePath;
        $this->waterMarkPath = $markPath;
        $this->newWidth = $new_width ? $new_width : $this->width;
        $this->newHeight = $new_height ? $new_height : $this->height;
        $this->quality = $quality ? $quality : 75;

        list($this->width, $this->height, $this->type) = getimagesize($this->imgPath);
        $this->img = $this->_loadImg($this->imgPath, $this->type);


        //生成縮略圖
        $this->_thumb();
        //添加水印圖片
        if (!empty($this->waterMarkPath)) $this->_addWaterMark();
        //輸出圖片
        $this->_outputImg();
    }

 Note: 先生成縮略圖,再在新圖上添加水印 圖片。

 

   5.2. 生成縮略圖函數_thumb() 

     /**
     * 縮略圖(按等比例,根據設置的寬度和高度進行裁剪)
     */
    private function _thumb()
    {

        //如果原圖本身小於縮略圖,按原圖長高
        if ($this->newWidth > $this->width) $this->newWidth = $this->width;
        if ($this->newHeight > $this->height) $this->newHeight = $this->height;

        //背景圖長高
        $gd_width = $this->newWidth;
        $gd_height = $this->newHeight;

        //如果縮略圖寬高,其中有一邊等於原圖的寬高,就直接裁剪
        if ($gd_width == $this->width || $gd_height == $this->height) {
            $this->newWidth = $this->width;
            $this->newHeight = $this->height;
        } else {

            //計算縮放比率
            $per = 1;

            if (($this->newHeight / $this->height) > ($this->newWidth / $this->width)) {
                $per = $this->newHeight / $this->height;
            } else {
                $per = $this->newWidth / $this->width;
            }

            if ($per < 1) {
                $this->newWidth = $this->width * $per;
                $this->newHeight = $this->height * $per;
            }
        }

        $this->newImg = $this->_CreateImg($gd_width, $gd_height, $this->type);
        imagecopyresampled($this->newImg, $this->img, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
    }

生成縮略圖函數_thumb() ,是按照前面的分析來進行編碼。  

   5.3. 添加水印圖片函數 _addWaterMark()     

     /**
     * 添加水印
     */
    private function _addWaterMark()
    {
        $ratio = 1 / 5; //水印縮放比率

        $Width = imagesx($this->newImg);
        $Height = imagesy($this->newImg);

        $n_width = $Width * $ratio;
        $n_height = $Width * $ratio;

        list($markWidth, $markHeight, $markType) = getimagesize($this->waterMarkPath);

        if ($n_width > $markWidth) $n_width = $markWidth;
        if ($n_height > $markHeight) $n_height = $markHeight;

        $Img = $this->_loadImg($this->waterMarkPath, $markType);
        $Img = $this->_thumb1($Img, $markWidth, $markHeight, $markType, $n_width, $n_height);
        $markWidth = imagesx($Img);
        $markHeight = imagesy($Img);
        imagecopyresampled($this->newImg, $Img, $Width - $markWidth - 10, $Height - $markHeight - 10, 0, 0, $markWidth, $markHeight, $markWidth, $markHeight);
        imagedestroy($Img);
    }

在添加水印圖片中,用到一個_thumb1()函數來縮放水印圖片:

    /**
     * 縮略圖(按等比例)
     * @param resource $img 圖像流
     * @param int $width
     * @param int $height
     * @param int $type
     * @param int $new_width
     * @param int $new_height
     * @return resource
     */
    private function _thumb1($img, $width, $height, $type, $new_width, $new_height)
    {

        if ($width < $height) {
            $new_width = ($new_height / $height) * $width;
        } else {
            $new_height = ($new_width / $width) * $height;
        }

        $newImg = $this->_CreateImg($new_width, $new_height, $type);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        return $newImg;
    }

   5.4. 完整代碼:

<?php

/**
 * 圖片處理,生成縮略圖和添加水印圖片
 * Created by PhpStorm.
 * User: andy
 * Date: 17-1-3
 * Time: 上午11:55
 */
class Image
{
    //原圖
    private $imgPath;   //圖片地址
    private $width;     //圖片寬度
    private $height;    //圖片高度
    private $type;      //圖片類型
    private $img;       //圖片(圖像流)

    //縮略圖
    private $newImg;    //縮略圖(圖像流)
    private $newWidth;
    private $newHeight;

    //水印圖路徑
    private $waterMarkPath;

    //輸出圖像質量,jpg有效
    private $quality;

    /**
     * Image constructor.
     * @param string $imagePath 圖片路徑
     * @param string $markPath 水印圖片路徑
     * @param int $new_width 縮略圖寬度
     * @param int $new_height 縮略圖高度
     * @param int $quality JPG圖片格輸出質量
     */
    public function __construct(string $imagePath,
                                string $markPath = null,
                                int $new_width = null,
                                int $new_height = null,
                                int $quality = 75)
    {
        $this->imgPath = $_SERVER['DOCUMENT_ROOT'] . $imagePath;
        $this->waterMarkPath = $markPath;
        $this->newWidth = $new_width ? $new_width : $this->width;
        $this->newHeight = $new_height ? $new_height : $this->height;
        $this->quality = $quality ? $quality : 75;

        list($this->width, $this->height, $this->type) = getimagesize($this->imgPath);
        $this->img = $this->_loadImg($this->imgPath, $this->type);


        //生成縮略圖
        $this->_thumb();
        //添加水印圖片
        if (!empty($this->waterMarkPath)) $this->_addWaterMark();
        //輸出圖片
        $this->_outputImg();
    }

    /**
     *圖片輸出
     */
    private function _outputImg()
    {
        switch ($this->type) {
            case 1: // GIF
                imagegif($this->newImg, $this->imgPath);
                break;
            case 2: // JPG
                if (intval($this->quality) < 0 || intval($this->quality) > 100) $this->quality = 75;
                imagejpeg($this->newImg, $this->imgPath, $this->quality);
                break;
            case 3: // PNG
                imagepng($this->newImg, $this->imgPath);
                break;
        }
        imagedestroy($this->newImg);
        imagedestroy($this->img);
    }

    /**
     * 添加水印
     */
    private function _addWaterMark()
    {
        $ratio = 1 / 5; //水印縮放比率

        $Width = imagesx($this->newImg);
        $Height = imagesy($this->newImg);

        $n_width = $Width * $ratio;
        $n_height = $Width * $ratio;

        list($markWidth, $markHeight, $markType) = getimagesize($this->waterMarkPath);

        if ($n_width > $markWidth) $n_width = $markWidth;
        if ($n_height > $markHeight) $n_height = $markHeight;

        $Img = $this->_loadImg($this->waterMarkPath, $markType);
        $Img = $this->_thumb1($Img, $markWidth, $markHeight, $markType, $n_width, $n_height);
        $markWidth = imagesx($Img);
        $markHeight = imagesy($Img);
        imagecopyresampled($this->newImg, $Img, $Width - $markWidth - 10, $Height - $markHeight - 10, 0, 0, $markWidth, $markHeight, $markWidth, $markHeight);
        imagedestroy($Img);
    }

    /**
     * 縮略圖(按等比例,根據設置的寬度和高度進行裁剪)
     */
    private function _thumb()
    {

        //如果原圖本身小於縮略圖,按原圖長高
        if ($this->newWidth > $this->width) $this->newWidth = $this->width;
        if ($this->newHeight > $this->height) $this->newHeight = $this->height;

        //背景圖長高
        $gd_width = $this->newWidth;
        $gd_height = $this->newHeight;

        //如果縮略圖寬高,其中有一邊等於原圖的寬高,就直接裁剪
        if ($gd_width == $this->width || $gd_height == $this->height) {
            $this->newWidth = $this->width;
            $this->newHeight = $this->height;
        } else {

            //計算縮放比率
            $per = 1;

            if (($this->newHeight / $this->height) > ($this->newWidth / $this->width)) {
                $per = $this->newHeight / $this->height;
            } else {
                $per = $this->newWidth / $this->width;
            }

            if ($per < 1) {
                $this->newWidth = $this->width * $per;
                $this->newHeight = $this->height * $per;
            }
        }

        $this->newImg = $this->_CreateImg($gd_width, $gd_height, $this->type);
        imagecopyresampled($this->newImg, $this->img, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
    }


    /**
     * 縮略圖(按等比例)
     * @param resource $img 圖像流
     * @param int $width
     * @param int $height
     * @param int $type
     * @param int $new_width
     * @param int $new_height
     * @return resource
     */
    private function _thumb1($img, $width, $height, $type, $new_width, $new_height)
    {

        if ($width < $height) {
            $new_width = ($new_height / $height) * $width;
        } else {
            $new_height = ($new_width / $width) * $height;
        }

        $newImg = $this->_CreateImg($new_width, $new_height, $type);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        return $newImg;
    }

    /**
     * 載入圖片
     * @param string $imgPath
     * @param int $type
     * @return resource
     */
    private function _loadImg($imgPath, $type)
    {
        switch ($type) {
            case 1: // GIF
                $img = imagecreatefromgif($imgPath);
                break;
            case 2: // JPG
                $img = imagecreatefromjpeg($imgPath);
                break;
            case 3: // PNG
                $img = imagecreatefrompng($imgPath);
                break;
            default: //其他類型
                Tool::alertBack('不支持當前圖片類型.' . $type);
                break;
        }
        return $img;
    }

    /**
     * 創建一個背景圖像
     * @param int $width
     * @param int $height
     * @param int $type
     * @return resource
     */
    private function _CreateImg($width, $height, $type)
    {
        $img = imagecreatetruecolor($width, $height);
        switch ($type) {
            case 3: //png
                imagecolortransparent($img, 0); //設置背景為透明的
                imagealphablending($img, false);
                imagesavealpha($img, true);
                break;
            case 4://gif
                imagecolortransparent($img, 0);
                break;
        }

        return $img;
    }
}
Image.class.php

 

6.調用

調用非常簡單,在引入類後,直接new 並輸入對應參數即可:

e.g.

new Image($_path, MARK, 400, 200, 100);

7.小結

      這個Image 類能夠生成縮略圖,不出現黑邊,添加水印圖,能根據圖片的大小縮放水印圖。當然有個缺點,就是不能縮放GIF的動畫,因為涉及到幀的處理,比較麻煩。

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在2.3中完成依賴註入後,這次主要實現欄目的添加功能。按照前面思路欄目有三種類型,常規欄目即可以添加子欄目也可以選擇是否添加內容,內容又可以分文章或其他類型,所以還要添加一個模塊功能。這次主要實現欄目的添加,附帶實現模塊列表功能,並將業務邏輯層的功能都實現了非同步方法。 先來個完成後的界面吧。 一、業... ...
  • 上一篇, 都是從別人那裡拷過來的, 主要是介紹規則和說明的. 這一篇, 才是重點, 講實際使用. 首先介紹項目中最常用的配置文件方式. 一、log4net.config 文件方式 我習慣, 把log4net的配置, 放在一個單獨的配置文件中, 而不是放在 app.config或者web.config ...
  • 再簡單的功能,也需要一坨代碼的支持。Profile 的編輯功能主要就是修改個人的信息。比如用戶名、頭像、性別、電話……雖然只是一個編輯界面,但添加下來,涉及了6個文件的修改和7個新創建的文件。各種生成的和手寫的代碼,共有934行之多。 1. Account 和 Profile 分離 什麼是 Acco ...
  • 項目過程中, 不可避免的, 需要使用到日誌功能. 在我接觸過的項目中, 也有自己弄一套日誌的, 但是更多的, 還是使用別人成熟的dll, 比如log4. log4相關的文檔, 真是非常的多, 也非常的全, 但是本著溫故而知新的目的, 還是想把這個過一遍. 先放一個小Demo在上面 主要有五個組成部分 ...
  • 現在這個時代是信息化的時代,大數據的時代。各種行業都在向線上管理等方向轉型。這時一系列的問題就自然而然的出來了。信息化管理的公司、企業,如何來開發設計自己的管理系統?選擇何種渠道來獲取符合自己需求的管理系統? 在這個時代,軟體公司遍地可尋。軟體開發行業蓬勃發展。儘管有這麼多的資源和產品,總多企業仍然 ...
  • 眼看快到婚期了,我在單位愉快的加著班!本人出身農村,11年畢業於一個不上檔次的院校,在學校里學的是電腦相關專業,這種專業在家裡基本上是不太好找工作的,想想好多學長帶著夢想去了北上廣深等地發展,畢竟這種行業在這些大城市裡比較發達。畢業之後,我孤身一人帶著我的北漂夢想,踏上了去往北京的征途。來了北京不 ...
  • ThinkPHP 模板substr的截取字元串函數在Common/function.php加上以下代碼 前端頁面需要截取字元串時 /********************************************案例************************************** ...
  • 前端獲取數據: thinkphp讀取資料庫數據: ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...