推薦一個 PHP 影象處理操作外掛 Intervention Image

coding01發表於2017-11-11

無論 Web 前端,還是 APP 開發,都避免不了和影象處理打交道,對於前端來說,影象處理都還好說,也比較簡單。

但對於應用後臺,或者介面而言,畢竟主要工作是處理資料的,影象處理方面比較少,但是現在後臺處理圖片功能,也會越來越多,如在公眾號,要實現特定海報生成功能,這時候就需要將粉絲使用者的頭像和暱稱內嵌到固定的圖片上,製作成海報,分享朋友圈,起到宣傳作用。

所以今天特向 PHP 工程師們推薦一個 Intervention Image 圖片處理外掛。

Intervention Image

Intervention/image 是為 Laravel 定製的圖片處理工具, 它提供了一套易於表達的方式來建立、編輯圖片。

Intervention Image is an open source PHP image handling and manipulation library. It provides an easier and expressive way to create, edit, and compose images and supports currently the two most common image processing libraries GD Library and Imagick.

The class is written to make PHP image manipulating easier and more expressive. No matter if you want to create image thumbnails, watermarks or format large image files Intervention Image helps you to manage every task in an easy way with as little lines of code as possible.

The library follows the FIG standard PSR-2 to ensure a high level of interoperability between shared PHP code and is fully unit-tested.

摘自官網 image.intervention.io/

安裝 Intervention Image

本文結合 Laravel 專案介紹 Intervention Image 基本使用,所以使用 composer 來安裝 Intervention Image 再適合不過了,而且 Intervention Image 官網也推薦使用 composer 來安裝。

composer require intervention/image

// 或者

php composer.phar require intervention/image複製程式碼

如何安裝 Composer,可以看看我之前的文章

d.laravel-china.org/docs/5.5/in…

Laravel 配置

在 config/app.php 配置檔案的$providers陣列中加入 provider:

Intervention\Image\ImageServiceProvider::class複製程式碼

$aliases 陣列中加入對應的 aliase:

'Image' => Intervention\Image\Facades\Image::class複製程式碼

如果需要配置 Image Driver,只需要在配置檔案config/image.php中修改,配置檔案只需要執行對應的命令生成即可:

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"複製程式碼

配置檔案如下:

<?php

return array(

    /*
    |--------------------------------------------------------------------------
    | Image Driver
    |--------------------------------------------------------------------------
    |
    | Intervention Image supports "GD Library" and "Imagick" to process images
    | internally. You may choose one of them according to your PHP
    | configuration. By default PHP's "GD Library" implementation is used.
    |
    | Supported: "gd", "imagick"
    |
    */

    'driver' => 'gd'

);複製程式碼

如果需要改成 Imagick 驅動,只需要把 driver 值改了就好。

開始影象處理之旅

Route::get('/yemeishu/{value}', function ($value) {

    $img = Image::make(base_path().'/***/background0.jpeg');

    return $img->response('jpeg');
});複製程式碼

這樣,就可以直接輸出這張圖片,當然我們可以在這張圖片上加上一段話:「I like Laravel」,再輸出:600*800大小。

Route::get('/yemeishu/{value}', function ($value) {

    $img = Image::make(base_path().'/***/background0.jpeg')->resize(600, 800);

    $img->text('「我喜歡 Laravel」', 120, 220, function ($font) {

        $font->file(base_path().'/***/font1.ttf');

        $font->size(32);

        $font->valign('bottom');

        $font->color('#333333');
    });

    return $img->response('jpeg');
});複製程式碼

接著我們再往上面放個「二維碼影象」,這個二維碼是個 url 連結:

Route::get('/yemeishu/{value}', function ($value) {
    $img = Image::make(base_path().'/public/***/background0.jpeg')->resize(600, 800);

    $img->text('「我喜歡 Laravel」', 120, 220, function ($font) {
        $font->file(base_path().'/***/font1.ttf');
        $font->size(32);
        $font->valign('bottom');
        $font->color('#333333');
    });

    // 獲取遠端圖片

    $erweimaimage = Image::make('http://ow20g4tgj.bkt.clouddn.com/2017-11-11-15103969491817.jpg')->resize(200, 200);

    // 插入到底部,下邊距 50 處
    $img->insert($erweimaimage, 'bottom', 0, 50);

    return $img->response('jpeg');
});複製程式碼

這樣就有種「海報」的感覺了吧。

接下來讓我們進入有點「料」的。在實際生成中,我們的海報主要由設計師設計出來後,開發人員切圖,然後落實成為具體的功能實現出來。

直接上程式碼:

public function getBookImageMaker($book, $share, $xcxurl) {
        $background = [
            base_path().'/public/***/background0.jpeg',
            base_path().'/public/***/background1.jpeg',
            base_path().'/public/***/background2.jpeg'
        ];

        $font_paths =  [base_path().'/***/font0.ttf',
            base_path().'/***/font1.ttf'];

        $font_path = $font_paths[rand(0, 1)];
        $img = Image::make($background[rand(0,2)])->resize(640, 1000);

        $face_img = Image::make($share['face_img'])
            ->resize(60, 60);
        // 頭部加頭像
        $img->insert(
            $face_img,
            'top-left',
            55,
            76
        );

        // 頭部加暱稱
        $img->text($share['nickname'].'為你推薦', 131, 120, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(32);
            $font->valign('bottom');
            $font->color('#333333');
        });

        // 圖書圖片區域
        $bodyimage = Image::canvas(533, 475, '#fe7e86');

        $goodsimage = Image::make($book['goods_img'])
            ->resize(531, 309);

        $bodyimage->insert($goodsimage, 'top-left', 1, 1);

        $bodybuttomimage = Image::canvas(531, 164, '#fff');

        $strings =  $this->mbStrSplit($book['name'], 18);

        $i = 0; //top position of string
        if (count($strings) == 1) {
            $bodybuttomimage->text($strings[0], 17, 44, function ($font) use ($font_path) {
                $font->file($font_path);
                $font->size(30);
                $font->valign('top');
                $font->color('#333333');
            });
        } else {
            foreach($strings as $key => $string) {
                if ($key == 2) {
                    break;
                }
                // 標題部分
                $bodybuttomimage->text($string, 17, 16 + $i, function ($font) use ($font_path) {
                    $font->file($font_path);
                    $font->size(27);
                    $font->valign('top');
                    $font->color('#333333');
                });
                $i = $i + 43; //shift top postition down 42
            }
        }

        // 價格
        if ($book['orig_price']) {
            $price = $book['orig_price'];
        } else {
            $price = $book['price'];
        }
        $bodybuttomimage->text('原價:'.$price, 17, 118, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('top');
            $font->color('#a3a3a3');
        });

        if ($book['group'] && $book['group']['endtime'] > date("Y-m-d H:i:s")) {
            $xianjiaString = '團購價:';
            $xianPrice = $book['group']['price'];

            $tuanButton = Image::canvas(107, 33, '#ff0000');

            $tuanButton->text($book['group']['min_quantity'].'人團', 22, 6, function ($font) use ($font_path) {
                $font->file($font_path);
                $font->size(25);
                $font->align('left');
                $font->valign('top');
                $font->color('#fff');
            });

            $bodybuttomimage->insert($tuanButton, 'top-right', 30, 110);
        } else {
            $xianjiaString = '現價:';
            $xianPrice = $book['price'];
        }

        $bodybuttomimage->text($xianjiaString, 180, 118, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(24);
            $font->valign('top');
            $font->color('#333333');
        });

        $bodybuttomimage->text('¥'.$xianPrice, 270, 118, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(27);
            $font->valign('top');
            $font->color('#fe0000');
        });
        $bodyimage->insert($bodybuttomimage, 'top-left', 1, 310);
        $img->insert($bodyimage, 'top-left', 55, 154);

        // 底部二維碼部分
        $dibuimage = Image::canvas(596,308);

        $codeimage = Image::make(base_path().'/public/img/maker/1/codeborder.jpeg')->resize(255, 255);
        $codesourceimage = Image::make($xcxurl)
            ->resize(249, 249);
        $codeimage->insert($codesourceimage, 'top-left', 3, 3);

        $dibuimage->insert($codeimage, 'top-left', 33, 23);

        $dibuimage->text('長按識別小程式碼', 300, 110, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(27);
            $font->valign('top');
            $font->color('#333333');
        });

        $dibuimage->text('立即搶購!', 370, 150, function ($font) use ($font_path) {
            $font->file($font_path);
            $font->size(27);
            $font->valign('top');
            $font->color('#333333');
        });

        $img->insert($dibuimage, 'top-left', 22, 650);

        return $img;
    }複製程式碼

最終的成品如下:

至於上述程式碼的函式作用可以參考官網 api 說明:

image.intervention.io/

總結

現在各種電商、內容應用平臺,各種公眾號宣傳等都會用到「海報」,如何在後臺介面製作各種個性化標籤的嵌入式海報,應該是個剛需。所以本文推薦使用 Intervention Image 外掛。

推薦閱讀

  1. 推薦一個 PHP 網路請求外掛 Guzzle mp.weixin.qq.com/s/w2I8hUmHu…

  2. 推薦一個 Laravel admin 後臺管理外掛 mp.weixin.qq.com/s/PnAj0j2X3…

「完」


coding01 期待您繼續關注

qrcode
qrcode


也很感謝您能看到這了

qrcode
qrcode

相關文章