PHP等比例缩放图片大小压缩图片空间

Php 2019-12-05 阅读 1026 评论 0

PHP做前后端图片上传的时候,经常需要做图片缩放处理。大部分是用了GD库和图像处理函数。

下面一个简单的代码工具,实现了等比例缩放图片大小,使用背景颜色填充,同时,支持压缩图片质量,减少图片占用空间,支持gif、jpg、jpeg、png。

使用imagefill方法区域填充,绘制背景颜色。

下面是等比例缩放图的代码,使用imagecopyresampled方法重采样拷贝部分图像并调整大小:

/**
 * 等比例压缩图片,支持图片格式jpg,jpeg,png
 * @param string $dst_dir	上传的文件夹
 * @param string $dst_name	上传后的名称,不包括扩展名
 * @param int $maxWidth	如果需要等比例压缩图片,指定压缩后的最大宽度,默认为200
 * @param int $maxHeight	如果需要等比例压缩图片,指定压缩后的最大高度,默认为200
 * @return boolean	成功返回true,否则返回false
 */
private function resize_image_and_keep_ratio() {
	//设置描绘的x、y坐标,高度、宽度
	$dst_x = $dst_y = $src_x = $src_y = 0;
	$ratio = min ( $this->given_height / $this->original_info['height'], $this->given_width / $this->original_info['width'] );
	$dst_h = ceil ( $this->original_info['height'] * $ratio );
	$dst_w = ceil ( $this->original_info['width'] * $ratio );
	$dst_x = ($this->given_width - $dst_w)/2;
	$dst_y = ($this->given_height - $dst_h)/2;
	return $this->copy($this->given_width, $this->given_height, $dst_x, $dst_y, $src_x, $src_y, 
			$dst_w, $dst_h);
}


/**
 * copy original image to new size
 * @param int $dst_w
 * @param int $dst_h
 * @param int $dst_x
 * @param int $dst_y
 * @param int $src_x
 * @param int $src_y
 * @param int $draw_w
 * @param int $draw_h
 * @return boolean
 */
private function copy($dst_w, $dst_h, $dst_x=0, $dst_y=0, $src_x=0, $src_y=0, $draw_w=0, $draw_h=0){
	// Generate new GD image
	$new = imagecreatetruecolor($dst_w, $dst_h);
	$draw_w = $draw_w == 0 ? $this->original_info['width'] : $draw_w;
	$draw_h = $draw_h == 0 ? $this->original_info['height'] : $draw_h;
	if( $this->original_info['format'] === 'gif' ) {
		// Preserve transparency in GIFs
		$transparent_index = imagecolortransparent($this->image);
		$palletsize = imagecolorstotal($this->image);
		if ($transparent_index >= 0 && $transparent_index < $palletsize) {
			$transparent_color = imagecolorsforindex($this->image, $transparent_index);
			$transparent_index = imagecolorallocate($new, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
			imagefill($new, 0, 0, $transparent_index);
			imagecolortransparent($new, $transparent_index);

			if (!empty($this->bgcolor)) {
				$bg = imagecolorallocate($new, $this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]);
				imagefill($new, 0, 0, $bg);
			}
		}
	} else {
		// Preserve transparency in PNGs (benign for JPEGs)
		imagealphablending($new, false);
		imagesavealpha($new, true);
		$color = imagecolorallocatealpha($new, 0, 0, 0, 127);
		imagefill($new, 0, 0, $color);
		if (!empty($this->bgcolor)) {
			$bg = imagecolorallocate($new, $this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]);
				imagefill($new, 0, 0, $bg);
		}
	}
	
	// Resize
	$flag = imagecopyresampled ( $new, $this->image, $dst_x, $dst_y, $src_x, $src_y, $draw_w, $draw_h, 
			$this->original_info['width'], $this->original_info['height'] );
	if ($flag) {
		$this->image = $new;
		$this->original_info['width'] = $dst_w;
		$this->original_info['height'] = $dst_h;
	} else {
		throw new \Exception ( 'copy image error' );
	}
	return $flag;
}

使用方法如下:

use com\jdk5\blog\Image\Image;
require '../Image.php';

$img = new Image();
$img->load('org.jpg')
	//->width(200)	//设置生成图片的宽度,高度将按照宽度等比例缩放
	//->height(200)	//设置生成图片的高度,宽度将按照高度等比例缩放
	->size(300, 300)	//设置生成图片的宽度和高度
	->fixed_given_size(true)	//生成的图片是否以给定的宽度和高度为准
	->keep_ratio(true)		//是否保持原图片的原比例
	->bgcolor("#ffffff")	//设置背景颜色,按照rgb格式
	->quality(50)	//设置生成图片的质量 0-100,如果生成的图片格式为png格式,数字越大,压缩越大,如果是其他格式,如jpg,gif,数组越小,压缩越大
	->save('processed/org-width-resize.jpg');	//保存生成图片的路径


原图  420 x 140

压缩后的图片如下:

400 x 100

200 x 200


源代码下载:前往下载

最后更新 2019-12-05
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });