改变图片的尺寸是一个很常见的功能需求,可以再客户端利用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;
}
?>
<##ads_in_article_manong##>
函数二:
<?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);
?> 继续阅读与本文标签相同的文章
下一篇 :
重返巅峰之路,纳德拉打造开源的微软
-
互联网之光大会的黑科技,总有一款惊艳你!
2026-05-14栏目: 教程
-
微信宣布一项新举措,关系到每一个用户,网友一致力挺:干得漂亮!
2026-05-14栏目: 教程
-
微软建议企业客户卸载KB4520062累积更新
2026-05-14栏目: 教程
-
他让我国芯片研究停滞13年,还骗走11亿研发资金,现状如何?
2026-05-14栏目: 教程
-
健乐教学机器人可开展的教学实训内容
2026-05-14栏目: 教程
