PHP自適應寬高度等比例縮圖函式 (無裁切)
對於產品類或者圖片類網站來說,縮圖是一個很重要的應用。其實說來很簡單,也就是把大圖縮放成一個小圖,用於圖片的列表展示,這樣可以達到使用者快速瀏覽的目的,又能節省頻寬。
如果是等比例縮放,比如小圖是大圖的1/2或者1/5之類的,比較容易處理。但有時候我們需要處理大量不同尺寸的大圖,讓其生成固定寬高度的縮圖。那就需要一種自適應的方式縮放,就是大圖在縮放的過程中,如果寬度先達到縮圖的寬度,那大圖多餘的高度就被裁剪掉;如果高度先達到縮圖的高度,那大圖多餘的寬度就被裁剪掉。這樣處理既讓縮圖不失真變形,又能最大化保留大圖內容。
今天用PHP寫了一個縮圖函式,可以達到這種自適應的等比例縮放效果。
<?php
/*
縮圖函式
作者:影子超
部落格:www.shadowchao.com
郵箱:
引數說明:
$w ---------- 縮圖寬度
$h ---------- 縮圖高度
$dst_path --- 縮圖路徑
$src_path --- 源影象路徑
*/
function zoom_image($w,$h,$dst_path,$src_path){
if(!file_exists($src_path)){
die("源影象檔案未找到!");
}
list($src_w,$src_h,$src_type)=getimagesize($src_path);
switch($src_type){
case 1:[email protected]
case 2:[email protected]($src_path);break;
case 3:[email protected]($src_path);break;
default:die("不能識別的影象型別!");
}
[email protected]($w,$h);
$scale_w=$src_w/$w;
$scale_h=$src_h/$h;
if($scale_w>$scale_h){
$src_w=$scale_h*$w;
}else{
$src_h=$scale_w*$h;
}
imagecopyresampled($dst_im,$src_im,0,0,0,0,$w,$h,$src_w,$src_h);
switch($src_type){
case 1:imagegif($dst_im,$dst_path,80);break;
case 2:imagejpeg($dst_im,$dst_path,80);break;
case 3:imagepng($dst_im,$dst_path,80);break;
}
imagedestroy($dst_im);
imagedestroy($src_im);
}
?>
函式共有4個引數,分別是你想生成的縮圖的寬度、高度、儲存的路徑以及大圖的檔案地址(可以是URL地址^_^)
呼叫方式如:zoom_image(100,100,"abc_small.jpg","abc_big.jpg"),呼叫無返回,直接將處理後的小圖存放在指定路徑下。
//生成縮圖(帶裁切)
function thum_img($img,$small_img){
$thumb = imagecreatetruecolor(100, 100);
$bg = imagecolorallocate($thumb, 255, 255, 255);
imagefilledrectangle($thumb, 0, 0, 100, 100, $bg);
$i = 0;
$j1 = $j2 = 190;
$imgarr = getimagesize($img);
if($imgarr['0']>$imgarr['1']){
$j1 = $imgarr['0']/($imgarr['1']/$j2);
$i = ceil(($j2-$j1)/2);
}elseif($imgarr['0']<=$imgarr['1']){
$j2 = $imgarr['1']/($imgarr['0']/$j2);
}
if($imgarr['mime']=='image/gif'){
$source = imagecreatefromgif($img);
}elseif($imgarr['mime']=='image/jpeg'){
$source = imagecreatefromjpeg($img);
}elseif($imgarr['mime']=='image/png'){
$source = imagecreatefrompng($img);
}elseif($imgarr['mime']=='image/bmp'){
$source = imagecreatefromwbmp($img);
}
imagecopyresampled($thumb, $source, $i, 0, 0, 0, $j1, $j2, $imgarr[0], $imgarr[1]);
return imagejpeg($thumb,$small_img);
}