PHP中的圖像的特殊處理——Grafika庫的使用

1.下載、部署和配置

下載
方法1.github: https://github.com/kosinix/grafika/
方法2.官網: https://kosinix.github.io/grafika/

部署
方法1.composer: composer require kosinix/grafika:dev-master --prefer-dist
方法2.直接下載,手動添加的項目中。
配置
每個示例都需要引入這個文件
require_once ‘src/autoloader.php’;

2. 基本使用

2.1基本處理——縮略圖生成

<?php
require_once './emotion/grafika/src/autoloader.php';
use Grafika\Grafika; // Import package
$editor = Grafika::createEditor();
$editor->open($image1 , './static/img/5.png');
$editor->resizeFit($image1 , 200 , 200); // resizeFit 等比縮放。resizeExact固定縮放
$editor->save($image1 , './static/img/10005.png');

在這裏插入圖片描述
縮略圖效果對比:
像素縮小:516x547 => 188x200
我們最初設置的200x200的意思是最長邊不超過200,然後等比縮放。保證圖片不失幀圖片的大小也有變化:74kb => 23kb

2.2其他縮放
我們前面講了等比縮放和固定縮放,那麼Grafika還支持那些功能呢?

  1. Resize Fill:$editor->resizeFill($image1 , 200,200);
    居中剪裁。就是把較短的變縮放到200px,然後將長邊的大於200px的部分居中剪裁掉,圖片不會變
  2. Resize Exact Width:$editor->resizeExactWidth($image1 , 200);
    等寬縮放,最終寬爲200px,等比縮放,高度不管。
  3. Resize Exact Height:
    等高縮放。最終高爲200px,等比縮放,不考慮圖片寬度。

2.3基本處理——其他功能

  1. 圖像對比功能
  2. 圖片合併功能
  3. 圖片寫文字
  4. 圖片旋轉
  5. 智能裁剪
  6. GIF縮略
  7. GIF動畫移除

3. 特效處理

3.1特效處理——圖像模糊

use Grafika\Grafika;
$editor = Grafika::createEditor();
$editor->open( $image, './static/img/5.png' );
$filter = Grafika::createFilter('Blur', 50); // 模糊度爲10,模糊度取值爲0-100
$editor->apply( $image, $filter ); // 將濾鏡應用到圖片
$editor->save($image,'./static/img/10006.png');

在這裏插入圖片描述
圖片像素沒變,大小變小。圖像變模糊。

3.2其他濾鏡功能

1.Brightness $filter = Grafika::createFilter('Brightness', -50);
亮度調整:-100 至 -1,變暗 0 圖片沒有變化 1-100圖片變亮
2.Colorize $filter = Grafika::createFilter('Colorize', -50,50,-50);
改變圖片顏色:取值-100至-1,顏色減少;爲0表示不變;取值1-100,表示色值增加
3.Contrast $filter = Grafika::createFilter('Contrast', 50);
改變對比度:-100至-1,對比度減少;0不變;1至100,對比度增加
4.Dither $filter = Grafika::createFilter('Dither', 'diffusion');
圖像添加噪點,其參數取值只有兩個diffusion:擴散;ordered:規整的
5.還有其他很多花裏胡哨的功能。

4. 屬性

4.1屬性處理——格式化爲二進制輸出
該方法的作用是打開一張圖片,然後格式化爲二進制數據,直接輸出到瀏覽器,而不是傳統的src顯
示圖片。
示例代碼:

use Grafika\Grafika;
$editor = Grafika::createEditor();
$editor->open( $image, './static/img/5.png' );
header('Content-type: image/png'); // Tell the browser we're sending a png image
$image->blob('PNG');

4.2其他屬性
1.getCore $result = $image->getCore();
獲取當前處理庫,是gd還是Imagick
2.getHeight $result = $image->getHeight();
獲取圖片高度,同樣獲取寬度用getWidth
3.getImageFile $result = $image->getImageFile();
獲取圖片當前文件名
4.getType $result = $image->getType();
獲取圖片類型
5. isAnimated $result = $image->isAnimated();
判斷是不是動態圖片

5. Grafika總結

在我們實際項目中,可以方便又快捷得生成縮咯圖或者模糊圖,這樣可以使我們的網站的加載速度大
大提高。我們還可以使用其靈活的裁剪功能,滿足我們網站顯示固定像素圖片的要求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章