PHP生成同比例的缩略图实现程序
在php中生成缩略图是程序开发中常用的,下面我找了几个不错的php生成缩略图的实现程序,有需要的朋友可使用,本人亲测绝对好用.
创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑,代码如下:
<?php
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
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;
}
//例2,代码如下
function creat_thumbnail($img, $w, $h, $path) {
$org_info = getimagesize($img); //获得图像大小且是通过post传递过来的
//var_dump($org_info);
//Array ( [0] => 1024 [1] => 768 [2] => 3 [3] => width="1024" height="768" [bits] => 8 [mime] => image/png )
$orig_x = $org_info[0]; //图像宽度
$orig_y = $org_info[1]; //图像高度
$orig_type = $org_info[2]; //图片类别即后缀 1 = GIF,2 = JPG,3 = PNG,
//是真彩色图像
if (function_exists("imagecreatetruecolor")) {
switch ($orig_type) {
//从给定的gif文件名中取得的图像
case 1:
$thumb_type = ".gif";
$_creatImage = "imagegif";
$_function = "imagecreatefromgif";
break;
//从给定的jpeg,jpg文件名中取得的图像
case 2:
$thumb_type = ".jpg";
$_creatImage = "imagejpeg";
$_function = "imagecreatefromjpeg";
break;
//从给定的png文件名中取得的图像
case 3:
$thumb_type = ".png";
$_creatImage = "imagepng";
$_function = "imagecreatefrompng";
break;
}
}
//如果从给定的文件名可取得的图像
if (function_exists($_function)) {
$orig_image = $_function($img); //从给定的$img文件名中取得的图像
}
if (($orig_x / $orig_y) >= (4 / 3)) //如果宽/高 >= 4/3
{
$y = round($orig_y / ($orig_x / $w)); //对浮点数进行四舍五入
$x = $w;
} else
//即 高/宽 >= 4/3
{
$x = round($orig_x / ($orig_y / $h));
$y = $h;
}
$sm_image = imagecreatetruecolor($x, $y); //创建真彩色图片
//重采样拷贝部分图像并调整大小
Imagecopyresampled($sm_image, $orig_image, 0, 0, 0, 0, $x, $y, $orig_x, $orig_y);
//imageJPEG($sm_image, '', 80); //在浏览器输出图像
$tnpath = $path . "/" . "s_" . date('YmdHis') . $thumb_type; //缩略图的路径
$thumbnail = @$_creatImage($sm_image, $tnpath, 80); //生成图片,成功返回true(或1)
imagedestroy($sm_image); //销毁图像
if ($thumbnail == true) {
return $tnpath;
}
}
?>文章网址:http://www.phprm.com/tuxiang/fs4419.html
随意转载^^但请附上教程地址。