按原等比率缩小,如果原图是透明的,处理后依旧保留透明
/** * 重置图片文件大小 * @param string $filePath 文件路径 * @param int $xmax 最大宽度 * @param int $ymax 最大高度 * @return boolean true/false */ public function ResetImageFileSize($filePath, $xmax, $ymax) { if(filesize($filePath) == 0) return 'error_file'; //$extension = pathinfo($filePath)['extension']; $extension = explode('/',getimagesize($filePath)['mime'])[1]; $img = null; switch ($extension) { case 'jpg': case 'jpeg': $img = imagecreatefromjpeg($filePath); break; case 'png': $img = imagecreatefrompng($filePath); break; case 'gif': $img = imagecreatefromgif($filePath); break; case 'webp': $img = imagecreatefromwebp($filePath); break; } if(is_null($img)) return false; list($x,$y) = getimagesize($filePath); if($x <= $xmax && $y <= $ymax){ return true; } /*保留原宽高比率*/ if($x >= $y) { $newX = ($x > $xmax) ? $xmax : $x; $newY = $newX * ($y / $x); }else{ $newY = ($y > $ymax) ? $ymax : $y; $newX = ($x / $y) * $newY; } $img2 = imagecreatetruecolor($newX, $newY); imageantialias($img2,true);//使用抗锯齿 if($extension == 'png'){ $Color = imagecolorallocatealpha($img2, 0, 0, 0, 127);//设置透明 }else{ $Color = imagecolorallocate($img2,255,255,255); } imagecolortransparent($img2,$Color); imagefill($img2,0,0,$Color); if(function_exists('imagecopyresampled')){ /*生成图像质量较好,但速度相比较慢*/ imagecopyresampled($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y); }else{ /*生成图像质量较差,但速度相比较快*/ imagecopyresized($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y); } switch ($extension) { case 'jpg': case 'jpeg': imagejpeg($img2,$filePath,100); break; case 'png': imagesavealpha($img2,true); imagepng($img2,$filePath); //imagepng($img2,$filePath,9); break; case 'gif': imagegif($img2,$filePath); break; default: imagejpeg($img2,$filePath,100); break; } imagedestroy($img2); return true; }
转载请注明本文标题和链接:《 PHP按原比率缩小图片并保留透明背景 》
网友评论 0