Sharpen an image using PHP and GD

同事正在開發一個購物平台,店家可以上傳商品照片,由系統自動縮圖到適合版面的大小,不過 resize 後圖片品質明顯下降,於是同事問我有沒有解法。同事問我並不是因為我比較強,只是因為我的位子在他旁邊。

跟同事討論了一下,試用了 imagecopyresizedimagecopyresampled 兩個函式來縮圖,前者的細節比較好,但部份線條出現明顯的變形,後者圖形正確,但看起來比較模糊。所以先用後者縮圖,再想辦法銳化圖片。

印象中 PHP GD Library 並沒有直接提供 sharpen (銳化) 相關的函式,但是 Google 一下,發現有 imageconvolution 濾鏡可以用,真是有趣,沒想到可以自訂濾鏡,以前在學校修過影像處理課程的回憶…. 都忘光光了。還好不難找到幾組範例。

<?php
// create the image resource from a file
$i = imagecreatefromjpeg('otter.jpg');

// define the sharpen matrix
$sharpen = array(
array(0.0, -1.0, 0.0),
array(-1.0, 5.0, -1.0),
array(0.0, -1.0, 0.0)
);

// calculate the sharpen divisor
$divisor = array_sum(array_map('array_sum', $sharpen));

// apply the matrix
imageconvolution($i, $sharpen, $divisor, 0);

// output the image
header('Content-Type: image/jpeg');
imagejpeg($i);
?>

隨便找一張圖做測試,效果如下。

PHP GD Sharpen Comparison

試了幾種參數組合,以下這組效果比較滿意。

array(0.0, -1.0, 0.0),
array(-1.0, 16.0, -1.0),
array(0.0, -1.0, 0.0)

Posted

in

by

Comments

One response to “Sharpen an image using PHP and GD”

  1. 魍魎姬 Avatar
    魍魎姬

    強者CQ!!!

Leave a Reply to 魍魎姬 Cancel reply

Your email address will not be published. Required fields are marked *