這篇文章主要介紹了PHP實作的自定義圖像居中裁剪函數,結合執行個體形式分析了php針對圖檔的擷取、計算、裁剪、儲存等相關操作技巧,需要的朋友可以參考下
具體如下:
圖像居中裁減的大緻思路:
1.首先将圖像進行縮放,使得縮放後的圖像能夠恰好覆寫裁減區域。(imagecopyresampled — 重采樣拷貝部分圖像并調整大小)
2.将縮放後的圖像放置在裁減區域中間。(imagecopy — 拷貝圖像的一部分)
3.裁減圖像并儲存。(imagejpeg | imagepng | imagegif — 輸出圖象到浏覽器或檔案)
具體代碼:
//==================縮放裁剪函數====================
function image_center_crop($source, $width, $height, $target)
{
if (!file_exists($source)) return false;
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
}
if (!isset($image)) return false;
$target_w = $width;
$target_h = $height;
$source_w = imagesx($image);
$source_h = imagesy($image);
$judge = (($source_w / $source_h) > ($target_w / $target_h));
$resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
$resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
$start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
$start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
$resize_img = imagecreatetruecolor($resize_w, $resize_h);
imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
$target_img = imagecreatetruecolor($target_w, $target_h);
imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
imagejpeg($target_img, $target);
break;
case IMAGETYPE_PNG:
imagepng($target_img, $target);
break;
case IMAGETYPE_GIF:
imagegif($target_img, $target);
break;
}
// return boolval(file_exists($target));//PHP5.5以上可用boolval()函數擷取傳回的布爾值
return file_exists($target)?true:false;//相容低版本PHP寫法
}
//==================函數使用方式====================
// 原始圖檔的路徑
$source = '../source/img/middle.jpg';
$width = 480; // 裁剪後的寬度
$height = 480;// 裁剪後的高度
// 裁剪後的圖檔存放目錄
$target = '../source/temp/resize.jpg';
// 裁剪後儲存到目标檔案夾
if (image_center_crop($source, $width, $height, $target)) {
echo "原圖1440*900為:
";
echo "
";
echo "修改後圖檔480*480為:
";
}
運作效果:
原圖1440*900為:
修改後圖檔480*480為:
同理,480*320,、800*600等尺寸的圖檔隻需修改相應參數即可。
附:代碼測試中遇到的問題
報錯:call an undefined function exif_imagetype()
解決方法:
打開擴充 extension=php_exif.dll
并将extension=php_mbstring.dll ,放到extension=php_exif.dll前邊
另:boolval()函數為PHP5.5版本以上才能使用的函數,本文測試代碼中為相容低版本,使用如下語句代替:
return file_exists($target)?true:false;
相關推薦: