php 压缩图片
时间: 2023-07-22 07:04:47 浏览: 64
你可以使用 PHP 的 GD 扩展来压缩图片。下面是一个简单的示例代码:
```php
// 原始图片路径
$source_image = 'path/to/image.jpg';
// 目标图片路径
$compressed_image = 'path/to/compressed_image.jpg';
// 目标图片质量(0-100)
$quality = 80;
// 获取原始图片信息
list($width, $height, $type) = getimagesize($source_image);
// 根据图片类型创建图像资源
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source_image);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source_image);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source_image);
break;
default:
throw new Exception('Unsupported image type.');
}
// 压缩图片
imagejpeg($image, $compressed_image, $quality);
// 释放图像资源
imagedestroy($image);
```
在上面的示例代码中,我们使用 `imagejpeg()` 函数将图像资源保存为 JPEG 格式,并指定了目标图片的路径和压缩质量。如果原始图片不是 JPEG 格式,你需要相应地使用 `imagepng()` 或 `imagegif()` 函数来保存图像资源。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)