PHP 图片压缩、图片缩放

使用 PHP 进行图片压缩,首先通过 imagecreatefrom* 系列函数创建源图像 resource 对象,再通过 imagecreate 或者 imagecreatetruecolor 函数创建确定宽度和高度的目标图像对象,接着进行一系列处理,最后通过 imagecopy* 系列函数把源图像对象拷贝到目标图像对象。完成上述处理之后,调用 imagegif、imagejpeg、imagepng 把目标图像对象转换为图像字符串输出到文件或者浏览器。似乎没有直接把图像对象转换为字符串的函数?可以通过 ob_start 捕获字符串输出,并调用 ob_get_clean 取得字符串。

imagecreatefrom* 系列函数

imagecreatefromgd 从 GD 文件或 URL 创建图像对象
imagecreatefromgd2 从 GD2 文件或 URL 创建图像对象
imagecreatefromgif 从 gif 文件创建图像对象
imagecreatefromjpeg 从 jpeg/jpg 文件创建图像对象
imagecreatefrompng 从 png 文件创建图像对象
imagecreatefromwbmp 从 wbmp 文件创建图像对象
imagecreatefromwebp 从 webp 文件创建图像对象
imagecreatefromxbm 从 xbm 文件创建图像对象
imagecreatefromxpm 从 xpm 文件创建图像对象
上述所有函数全部接收一个参数 — $filename, 失败时均会返回 false
imagecreatefromstring 从字符串创建图像对象
接收一个参数 — 图像二进制字符串

imagecopy* 系列函数

imagecopy 拷贝图像的一部分
imagecopymerge 拷贝并合并图像的一部分
imagecopymergegray 用灰度拷贝并合并图像的一部分
imagecopyresampled 重采样拷贝部分图像并调整大小
imagecopyresized 拷贝部分图像并调整大小

图片压缩实现代码

$image = 'D:\TEMP\woxinfeishi-bukezhuanye.jpg';
$source = imagecreatefromjpeg($image);

$s_width = imagesx($source);
$s_height = imagesy($source);

$max_width = 200;
$max_height = 200;

if ($s_width > $max_width
	|| $s_height > $max_height)
{
	$s_rate = $s_width / $s_height;
	$t_rate = $max_width / $max_height;

	if ($s_rate > $t_rate)
	{
		$t_width = $max_width;
		$t_height = floor($t_width / $s_rate);
	}
	else
	{
		$t_height = $max_height;
		$t_width = floor($t_height * $s_rate);
	}

	$target = imagecreatetruecolor($t_width,
		$t_height);
	imagecopyresampled($target, $source, 0, 0, 0, 0,
		$t_width, $t_height,
		$s_width, $s_height);
}
else
{
	$target = $source;
}

ob_start();
imagejpeg($target);
$image_data = ob_get_clean(); // 图像数据
imagedestroy($source);
imagedestroy($target);

上述代码实现图片等比压缩,如果是缩放到固定高宽则只需要直接设置为最终高宽。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注