php產生縮圖填充白邊(等比縮圖方案)_php執行個體

來源:互聯網
上載者:User

網站上傳圖片後產生縮圖應該是非常常用的功能了,通常來講為了網站顯示美觀,縮圖會是同樣尺寸,比如最近筆者做的一個網站,縮圖規格要求都是160×120。但是如果上傳的圖片比例和縮圖不一致,直接縮放的話就會導致圖片變形,這樣體驗肯定就不好了。於是筆者想了一個折中的辦法,就是縮小後添加白邊的方法。

源圖,尺寸是600×366:

最終產生的效果圖:

代碼相對比較長些,下面簡單說下思路:

先將源圖按比例產生縮圖,並且寬不大於160、高不大於120。例如上圖會先產生160×98的縮圖。
建立一個160×120的白色背景圖片,將上一步產生的縮圖置中放置到這張圖片上就OK了。
最終代碼如下:

複製代碼 代碼如下:

//源圖的路徑,可以是本地檔案,也可以是遠程圖片
$src_path = '1.jpg';
//最終儲存圖片的寬
$width = 160;
//最終儲存圖片的高
$height = 120;

//源圖對象
$src_image = imagecreatefromstring(file_get_contents($src_path));
$src_width = imagesx($src_image);
$src_height = imagesy($src_image);

//產生等比例的縮圖
$tmp_image_width = 0;
$tmp_image_height = 0;
if ($src_width / $src_height >= $width / $height) {
    $tmp_image_width = $width;
    $tmp_image_height = round($tmp_image_width * $src_height / $src_width);
} else {
    $tmp_image_height = $height;
    $tmp_image_width = round($tmp_image_height * $src_width / $src_height);
}

$tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);
imagecopyresampled($tmpImage, $src_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);

//添加白邊
$final_image = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($final_image, 255, 255, 255);
imagefill($final_image, 0, 0, $color);

$x = round(($width - $tmp_image_width) / 2);
$y = round(($height - $tmp_image_height) / 2);

imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);

//輸出圖片
header('Content-Type: image/jpeg');
imagejpeg($final_image);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.