最近在處理小程序的圖片數據,需要對庫裏數據的圖片進行等比例放大縮小,自己也是網上找了一番,最終合成適用於放大、縮小並保存的例子,下面就跟大家分享這段代碼:
/**
* 處理圖片尺寸【等比例縮小或放大】
* @param $filePath【進行處理圖片本地地址】
* @param $saveImage【處理後保存地址】
* @param $maxWidth【最大寬度】
* @param $maxHeight【最大高度】
* @param $minWith【最小寬度】
* @param $minHeight【最小高度】
*/
function resizeImage($filePath, $saveImage, $maxWidth, $maxHeight, $minWith, $minHeight)
{
//獲取圖片基礎信息
$tmpImageSize = getimagesize($filePath);
$originalImageWidth = $tmpImageSize[0]; //寬度
$originalImageHeight = $tmpImageSize[1]; //長度
$originalImageType = $tmpImageSize[2]; //類型
//保存圖片的寬度跟高度
$targetWidth = $tmpImageSize[0];
$targetHeight = $tmpImageSize[1];
//計算圖片將要保存的尺寸
if ($originalImageWidth > $maxWidth) { //圖片寬度超過最大限度
$targetWidth = $maxWidth;
$targetHeight = $originalImageHeight * ($maxWidth / $originalImageWidth);
}
if ($originalImageWidth < $minWith) { //圖片寬帶小於最小限度
$targetWidth = $minWith;
$targetHeight = $originalImageHeight * ($minWith / $originalImageWidth);
}
if ($targetHeight > $maxHeight) { //圖片高度超過最大限度
$targetWidth = $targetWidth * ($maxHeight / $targetHeight);
$targetHeight = $maxHeight;
}
if ($targetHeight < $minHeight) { //圖片高度小於最小限度
$targetWidth = $targetWidth * ($minHeight / $targetHeight);
$targetHeight = $minHeight;
}
//最後檢驗寬度跟高度是否符合【兜底】
if ($targetWidth < $minWith) {
$targetWidth = $minWith;
}
if ($targetWidth > $maxWidth) {
$targetWidth = $maxWidth;
}
if ($targetHeight < $minHeight) {
$targetHeight = $minHeight;
}
if ($targetHeight > $maxHeight) {
$targetHeight = $maxHeight;
}
//四捨五入
$targetWidth = ceil($targetWidth);
$targetHeight = ceil($targetHeight);
//判斷圖片格式進行處理
if ($originalImageType == 1) {
$temPic = imagecreatefromgif($filePath);
} else if ($originalImageType == 2) {
$temPic = imagecreatefromjpeg($filePath);
} else if ($originalImageType == 3) {
$temPic = imagecreatefrompng($filePath);
} else {
exit();
}
//保存圖片
$thPic = imagecreatetruecolor($targetWidth, $targetHeight);
// 調整默認顏色
$color = imagecolorallocate($thPic, 255, 255, 255);
imagefill($thPic, 0, 0, $color);
//裁剪
imagecopyresampled($thPic, $temPic, 0, 0, 0, 0, $targetWidth, $targetHeight,
$originalImageWidth, $originalImageHeight);
//保存圖片
imagejpeg($thPic, $saveImage);
}
以上代碼就是處理根據我們的要求處理圖片的放大、縮小,下面就是如何引用的代碼:
resizeImage('image/123.jpg','image/321.jpg', 1024, 1024,200, 200);
這樣我們就成功可以對圖片進行放大、縮小並保存在本地。