php实现图片压缩功能

简述:

使用php的GD库可以将图片按固定宽高或者等比例压缩,主要利用的函数是:

imagecopyresampled:将一张图片中的一块区域复制到另一张图片上

等比例压缩

 

/**
	 * [compressImg description]
	 * @param  string  $src     源图片
	 * @param  integer $percent 压缩比例
	 * @return [type]           [description]
	 */
	public function compressImg($src = '', $percent = 1)
	{
		list($width, $height, $type, $attr) = getimagesize($src);
		$type = image_type_to_extension($type, false);
       
        $fun         = "imagecreatefrom" . $type;
        $image 		 = $fun($src);
        $new_width   = $width * $percent;
        $new_height  = $height * $percent;
        $thump = imagecreatetruecolor($new_width, $new_height);
        //将原图复制到另一张图片上,并且按照一定比例压缩
        imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        imagedestroy($image);
        $image = $thump;

        // 1、浏览器直接输出
        header('Content-Type: image/' . $type);
        $funcs = "image" . $type;
        $funcs($thump);

        // 2、保存到对应路径
        $path = 'save.'.$type;
        $funcs = "image" . $type;
        $funcs($thump, $path);
	}

按固定宽高压缩

/**
	 * [compressImgWH description]
	 * @param  string $src        源图片
	 * @param  string $new_width  压缩后宽度
	 * @param  string $new_height 压缩后高度
	 * @return [type]             [description]
	 */
	public function compressImgWH($src = '', $new_width='', $new_height=''){
		list($width, $height, $type, $attr) = getimagesize($src);
		$type = image_type_to_extension($type, false);
 
        $fun = "imagecreatefrom" . $type;
        $image = $fun($src);

        $thump = imagecreatetruecolor($new_width, $new_height);
        // 处理透明背景图片变成黑色的问题
        if(strtolower($type)=='png'){
            imageantialias($thump, true);
            $color = imagecolorallocate($thump, 255, 255, 255);
            imagecolortransparent($thump, $color);
            imagefill($thump, 0, 0, $color);
        }
        //将原图复制到其他图片上,并且按照一定宽高压缩
        imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        imagedestroy($image);

        // 1、浏览器直接输出
        header('Content-Type: image/' . $type);
        $funcs = "image" . $type;
        $funcs($thump);

        // 2、保存到对应路径
        $path = 'save.'.$type;
        $funcs = "image" . $type;
        $funcs($thump, $path);
	}

功能演示:

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值