php缩放图片,压缩图片处理。使用imagecopyresampled()函数重采样拷贝部分图像并调整大小,将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。
相关函数:
创建图像:
imagecreatefromgif():创建一块画布,并从 GIF 文件或 URL 地址载入一副图像
imagecreatefromjpeg():创建一块画布,并从 JPEG 文件或 URL 地址载入一副图像
imagecreatefrompng():创建一块画布,并从 PNG 文件或 URL 地址载入一副图像
imagecreatefromwbmp():创建一块画布,并从 WBMP 文件或 URL 地址载入一副图像
imagecreatefromstring():创建一块画布,并从字符串中的图像流新建一副图像
输出图像:
imagegif():以 GIF 格式将图像输出到浏览器或文件
imagejpeg():以 JPEG 格式将图像输出到浏览器或文件
imagepng():以 PNG 格式将图像输出到浏览器或文件
imagewbmp():以 WBMP 格式将图像输出到浏览器或文件
代码:
<?php // 这个文件 $filename = empty($_GET['name']) ? null : $_GET['name']; if (empty($filename)) { exit('图片地址不能为空!'); } $img_info = getimagesize($filename); //缩放比例 $percent = empty($_GET['percent']) ? 1 : $_GET['percent']; // 获取新的尺寸 $width = $img_info[0]; $height = $img_info[1]; $new_width = $width * $percent; $new_height = $height * $percent; // 内容类型 if ($img_info['mime'] == 'image/jpeg') { header('Content-Type: image/jpeg'); // 重新取样 $image_p = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // 输出 imagejpeg($image_p, null,100); } if ($img_info['mime'] == 'image/png') { header('Content-Type: image/png'); // 重新取样 $image_p = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefrompng($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // 输出 imagepng($image_p, null,100); } if ($img_info['mime'] == 'image/gif') { header('Content-Type: image/gif'); // 重新取样 $image_p = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromgif($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // 输出 imagegif($image_p, null,100); } ?>
浏览器访问并传图片地址和压缩比例。