php分享对图片大小(缩放)进行调整的函数

时间:2017-07-27
我用过一些php实现的图片大小调整(image resize)函数,但是都不是很完美,有的图片在调整之后完全变形。本文章向大家分享一个完美的利用php方法进行图片尺寸修改和储存的函数。需要的朋友可以参考一下。

改变图片的尺寸是一个很常见的功能需求,可以再客户端利用HTML或css来修改图片尺寸,但这种方法可能会使图片变形。最好的方法当然是在服务器端对图片进行剪切操作,操作为自己需要的尺寸。下面开始研究下关于PHP改变图片尺寸的方法。先介绍二个自己写的函数。

函数一:

使用以下代码修改图片大小或创建缩略图。

参数说明:

  • $filename:文件名。
  • $tmpname:文件路径,如上传中的临时目录。
  • $xmax:修改后最大宽度。
  • $ymax:修改后最大高度。
<?php
// 重置图片文件大小
function resize_image($filename, $tmpname, $xmax, $ymax)
{
	$ext = explode(".", $filename);
	$ext = $ext[count($ext)-1];
 
	if($ext == "jpg" || $ext == "jpeg")
		$im = imagecreatefromjpeg($tmpname);
	elseif($ext == "png")
		$im = imagecreatefrompng($tmpname);
	elseif($ext == "gif")
		$im = imagecreatefromgif($tmpname);
 
	$x = imagesx($im);
	$y = imagesy($im);
 
	if($x <= $xmax && $y <= $ymax)
		return $im;
 
	if($x >= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	}
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	}
 
	$im2 = imagecreatetruecolor($newx, $newy);
	imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
	return $im2; 
}
?>

函数二:

<?php

$imgsrc = "http://www.manongjc.com/images/3.jpg";
$width = 780;
$height = 420;

resizejpg($imgsrc,$imgdst,$width,$height);

function resizejpg($imgsrc,$imgdst,$imgwidth,$imgheight)
{ 
	//$imgsrc jpg格式图像路径 $imgdst jpg格式图像保存文件名 $imgwidth要改变的宽度 $imgheight要改变的高度
	//取得图片的宽度,高度值
	$arr = getimagesize($imgsrc);                     
	header("Content-type: image/jpg");
	
	$imgWidth = $imgwidth;
	$imgHeight = $imgheight;
	// Create image and define colors
	$imgsrc = imagecreatefromjpeg($imgsrc);
	$image = imagecreatetruecolor($imgWidth, $imgHeight);  //创建一个彩色的底图
	imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
	imagepng($image);
	imagedestroy($image);
}

?>

一个简单的示例:

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>