一款php批量生成缩略图代码

 更新时间:2016年11月25日 16:57  点击:1345

<?php教程
$oimg = "test.jpg";//original image name
$classes = array('translation','autoheight','autowidth','stretch');//give classes for the new creating images' size which are defined in the specified ini file
$suffix = 'jpg';//the new image's suffix
$inifile = 'image.ini.php';

$size = getimagesize($oimg);
$x = $size[0]/$size[1];
$name = explode('.',$oimg);

if(!file_exists($inifile)) die('ini file does not exist!');
$cn = parse_ini_file($inifile,true);//parse the class style image size from ini file
foreach($classes as $class){
    foreach($cn as $k=>$v){
        if($k==$class){
            if($v['width'] && $v['height']){
                $thumbwidth = $v['width'];
                $thumbheight = $v['height'];
            }elseif($v['width']){
                $thumbwidth = $v['width'];
                $thumbheight = round($thumbwidth/$x);
            }elseif($v['height']){
                $thumbheight = $v['height'];
                $thumbwidth = round($thumbheight*$x);
            }else{
                $thumbwidth = $size[0];
                $thumbheight = $size[1];
            }
            break;
        }
    }
    if(!isset($thumbheight) && !isset($thumbwidth)) die('ini file settings error!');

    $nimg = $name[0].'_'.$class.'.'.$suffix;//new image file name
    $source = imagecreatefromjpeg($oimg);
    $thumb = imagecreatetruecolor($thumbwidth, $thumbheight);
    imagecopyresampled($thumb,$source,0,0,0,0,$thumbwidth,$thumbheight,$size[0],$size[1]);

    if($suffix=='jpg') $method = 'imagejpeg';
    else $method='image'.$suffix;
    $method($thumb, $nimg);
    imagedestroy($thumb);//release the image source
    imagedestroy($source);
}
?>

缩放图片的php代码,其中变量classes是一个数组,可以选择任意多个ini文件中指定的设置:

这是一个ini配置文件,上面的代码就要读取这个文件中的图片位置,可以多个。

<?php /*
;translate the image format using the original image size
[translation]
width=0
height=0

;stretch the image to the specified size
[stretch]
width=800
height=600

;zoom the image to the specified width with height auto size
[autoheight]
width=740
height=0

;zoom the image to the specified height with width auto size
[autowidth]
width=0
height=380
*/ ?>

注意:ini文件使用php解释时为注释文件,什么也没有输出,这是为了安全起见而故意为之。而;则是ini文件的注释。

要做到替换所有图片或者是连接的alt title我们必须用到正则函数,下面看一个替换图片alt实例

*/

preg_replace('#alt="[^"]*"#i','alt="".$title.""',$str);

/*
mixed preg_replace ( mixed pattern, mixed replacement, mixed subject [, int limit])


在 subject 中搜索 pattern 模式的匹配项并替换为 replacement。如果指定了 limit,则仅替换 limit 个匹配,如果省略 limit 或者其值为 -1,则所有的匹配项都会被替换。

 


过滤所有html 标签
*/

$html_body ="<br />fdafdsa <div>内容</div>";
preg_replace("/(</?)(w+)([^>]*>)/e",
             "'1'.strtoupper('2').'3'",
             $html_body);


   
//更多详细内容请查看:php教程er/php-function/33530.htm">http://www.111cn.net/phper/php-function/33530.htm

先了解files函数

$_files数组内容如下:

$_files['myfile']['name']   客户端文件的原名称。
$_files['myfile']['type']   文件的 mime 类型,需要浏览器提供该信息的支持,例如"image/gif"。
$_files['myfile']['size']   已上传文件的大小,单位为字节。
$_files['myfile']['tmp_name']   文件被上传后在服务端储存的临时文件名,一般是系统默认。可以在php教程.ini的upload_tmp_dir 指定,但 用 putenv() 函数设置是不起作用的。
$_files['myfile']['error']   和该文件上传相关的错误代码。['error'] 是在 php 4.2.0 版本中增加的。下面是它的说明:(它们在php3.0以后成了常量)
  upload_err_ok
    值:0; 没有错误发生,文件上传成功。
  upload_err_ini_size
    值:1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
  upload_err_form_size
    值:2; 上传文件的大小超过了 html 表单中 max_file_size 选项指定的值。
  upload_err_partial
    值:3; 文件只有部分被上传。
  upload_err_no_file
    值:4; 没有文件被上传。
    值:5; 上传文件大小为0.

 

php代码

 

<?php
     $mkdir_file_dir    = mkdir('./img/'.$_post['title'],0777);           //上传文件的时候就开始创建一个图片相关的目录
     $tmp_file_name     = $_files['file']['tmp_name'];                        //上传成功之后取的临时文件名
     $file_name             = $_files['file']['name'];                        //原始的文件名
   
     $file_dir     = './img/'.$_post['title'].'/';                            //把创建的一个目录赋值给你一个变量作为最终的保存目录
    
     if(is_dir($file_dir))
     {
         move_uploaded_file($tmp_file_name,$file_dir.$file_name);        //开始移动文件
     }
 ?>

html代码

<html>
    <head>
        <title>
            my is upfile app!!
        </title>
        <meta    http-equiv="content-type" content="text/html;charset=utf-8" />
    </head>
    <body>
        <form enctype="multipart/form-data" method="post" action="upfile_add.php">
                标题:     <input type="text" name="title" />
                上传文件: <input type="file" name="file" />
                <input type="submit" vlaue="提交" />
        </form>
    </body>
</html>

非常重要的一点是:文件通过post提交后是保存在c:windowstemp临时文件夹中通过$_files["photo"]["tmp_name"],我们可以轻松获得上传的临时文件,将它保存到我们指定的路径中 下面是解决方案move_uploaded_file($_files["photo"]["tmp_name"],$path)

图片按在比较进行放大缩小,这得利用php教程 gd库的函数现实现,我们会利用到imagecreatetruecolor(),imagecopyresampled()来操作

function my_image_resize($src_file, $dst_file, $dst_width=32, $dst_height=32) {
    if($dst_width <1 || $dst_height <1) {
        echo "params width or height error !";
        exit();
    }
    if(!file_exists($src_file)) {
        echo $src_file . " is not exists !";
        exit();
    }

    $type=exif_imagetype($src_file);
    $support_type=array(imagetype_jpeg , imagetype_png , imagetype_gif);

    if(!in_array($type, $support_type,true)) {
        echo "this type of image does not support! only support jpg , gif or png";
        exit();
    }

    switch($type) {
        case imagetype_jpeg :
            $src_img=imagecreatefromjpeg($src_file);
            break;
        case imagetype_png :
            $src_img=imagecreatefrompng($src_file);        
            break;
        case imagetype_gif :
            $src_img=imagecreatefromgif($src_file);
            break;
        default:
            echo "load image error!";
            exit();
    }
    $src_w=imagesx($src_img);
    $src_h=imagesy($src_img);
    $ratio_w=1.0 * $dst_width/$src_w;
    $ratio_h=1.0 * $dst_height/$src_h;
    if ($src_w<=$dst_width && $src_h<=$dst_height) {
        $x = ($dst_width-$src_w)/2;
        $y = ($dst_height-$src_h)/2;
        $new_img=imagecreatetruecolor($dst_width,$dst_height);
        imagecopy($new_img,$src_img,$x,$y,0,0,$dst_width,$dst_height);
        switch($type) {
            case imagetype_jpeg :
                imagejpeg($new_img,$dst_file,100);
                break;
            case imagetype_png :
                imagepng($new_img,$dst_file);
                break;
            case imagetype_gif :
                imagegif($new_img,$dst_file);
                break;
            default:
                break;
        }
    } else {
        $dstwh = $dst_width/$dst_height;
        $srcwh = $src_w/$src_h;
        if ($ratio_w <= $ratio_h) {
            $zoom_w = $dst_width;
            $zoom_h = $zoom_w*($src_h/$src_w);
        } else {
            $zoom_h = $dst_height;
            $zoom_w = $zoom_h*($src_w/$src_h);
        }

        $zoom_img=imagecreatetruecolor($zoom_w, $zoom_h);
        imagecopyresampled($zoom_img,$src_img,0,0,0,0,$zoom_w,$zoom_h,$src_w,$src_h);
        $new_img=imagecreatetruecolor($dst_width,$dst_height);
        $x = ($dst_width-$zoom_w)/2;
        $y = ($dst_height-$zoom_h)/2+1;
        imagecopy($new_img,$zoom_img,$x,$y,0,0,$dst_width,$dst_height);
        switch($type) {
            case imagetype_jpeg :
                imagejpeg($new_img,$dst_file,100);
                break;
            case imagetype_png :
                imagepng($new_img,$dst_file);
                break;
            case imagetype_gif :
                imagegif($new_img,$dst_file);
                break;
            default:
                break;
        }
    }
}


总结,我们要生成比例生成小图就利用$dstwh = $dst_width/$dst_height;
        $srcwh = $src_w/$src_h;进行判断,然后再生成。

下面提供三款生成缩代码,兼容性都相当的不错,也可以自定高度与宽度哦。

function imageresize($srcfile,$tow,$toh,$tofile="")
{
if($tofile==""){ $tofile = $srcfile; }
$info = "";
$data = getimagesize($srcfile,$info);
switch ($data[2])
{
case 1:
if(!function_exists("imagecreatefromgif")){
echo "你的gd库不能使用gif格式的图片,请使用jpeg或png格式!<a href='网页特效:go(-1);'>返回</a>";
exit();
}
$im = imagecreatefromgif($srcfile);
break;
case 2:
if(!function_exists("imagecreatefromjpeg")){
echo "你的gd库不能使用jpeg格式的图片,请使用其它格式的图片!<a href='javascript:go(-1);'>返回</a>";
exit();
}
$im = imagecreatefromjpeg($srcfile);
break;
case 3:
$im = imagecreatefrompng($srcfile);
break;
}
$srcw=imagesx($im);
$srch=imagesy($im);
$towh=$tow/$toh;
$srcwh=$srcw/$srch;
if($towh<=$srcwh){
$ftow=$tow;
$ftoh=$ftow*($srch/$srcw);
}
else{
$ftoh=$toh;
$ftow=$ftoh*($srcw/$srch);
}
if($srcw>$tow||$srch>$toh)
{
if(function_exists("imagecreatetruecolor")){
@$ni = imagecreatetruecolor($ftow,$ftoh);
if($ni) imagecopyresampled($ni,$im,0,0,0,0,$ftow,$ftoh,$srcw,$srch);
else{
$ni=imagecreate($ftow,$ftoh);
imagecopyresized($ni,$im,0,0,0,0,$ftow,$ftoh,$srcw,$srch);
}
}else{
$ni=imagecreate($ftow,$ftoh);
imagecopyresized($ni,$im,0,0,0,0,$ftow,$ftoh,$srcw,$srch);
}
if(function_exists('imagejpeg')) imagejpeg($ni,$tofile);
else imagepng($ni,$tofile);
imagedestroy($ni);
}
imagedestroy($im);
}

实例代码二

<?php教程
/*构造函数-生成缩略图+水印,参数说明:
$srcfile-图片文件名,
$dstfile-另存文件名,
$markwords-水印文字,
$markimage-水印图片,
$dstw-图片保存宽度,
$dsth-图片保存高度,
$rate-图片保存品质*/
makethumb("a.jpg","b.jpg","50","50");
function makethumb($srcfile,$dstfile,$dstw,$dsth,$rate=100,$markwords=null,$markimage=null)
{
$data = getimagesize($srcfile);
switch($data[2])
{
case 1:
$im=@imagecreatefromgif($srcfile);
break;
case 2:
$im=@imagecreatefromjpeg($srcfile);
break;
case 3:
$im=@imagecreatefrompng($srcfile);
break;
}
if(!$im) return false;
$srcw=imagesx($im);
$srch=imagesy($im);
$dstx=0;
$dsty=0;
if ($srcw*$dsth>$srch*$dstw)
{
$fdsth = round($srch*$dstw/$srcw);
$dsty = floor(($dsth-$fdsth)/2);
$fdstw = $dstw;
}
else
{
$fdstw = round($srcw*$dsth/$srch);
$dstx = floor(($dstw-$fdstw)/2);
$fdsth = $dsth;
}
$ni=imagecreatetruecolor($dstw,$dsth);
$dstx=($dstx<0)?0:$dstx;
$dsty=($dstx<0)?0:$dsty;
$dstx=($dstx>($dstw/2))?floor($dstw/2):$dstx;
$dsty=($dsty>($dsth/2))?floor($dsth/s):$dsty;
$white = imagecolorallocate($ni,255,255,255);
$black = imagecolorallocate($ni,0,0,0);
imagefilledrectangle($ni,0,0,$dstw,$dsth,$white);// 填充背景色
imagecopyresized($ni,$im,$dstx,$dsty,0,0,$fdstw,$fdsth,$srcw,$srch);
if($markwords!=null)
{
$markwords=iconv("gb2312","utf-8",$markwords);
//转换文字编码
imagettftext($ni,20,30,450,560,$black,"simhei.ttf",$markwords); //写入文字水印
//参数依次为,文字大小|偏转度|横坐标|纵坐标|文字颜色|文字类型|文字内容
}
elseif($markimage!=null)
{
$wimage_data = getimagesize($markimage);
switch($wimage_data[2])
{
case 1:
$wimage=@imagecreatefromgif($markimage);
break;
case 2:
$wimage=@imagecreatefromjpeg($markimage);
break;
case 3:
$wimage=@imagecreatefrompng($markimage);
break;
}
imagecopy($ni,$wimage,500,560,0,0,88,31); //写入图片水印,水印图片大小默认为88*31
imagedestroy($wimage);
}
imagejpeg($ni,$dstfile,$rate);
imagejpeg($ni,$srcfile,$rate);
imagedestroy($im);
imagedestroy($ni);
}
?>

支持图片上传代码

<?php

 $pic_name=date("dmyhis");

 // 生成图片的宽度
 $pic_width=$_post['width'];

 // 生成图片的高度
 $pic_height=$_post['length'];

 function resizeimage($im,$maxwidth,$maxheight,$name){
  //取得当前图片大小
  $width = imagesx($im);
  $height = imagesy($im);
  //生成缩略图的大小
  if(($width > $maxwidth) || ($height > $maxheight)){
   $widthratio = $maxwidth/$width;  
   $heightratio = $maxheight/$height; 
   if($widthratio < $heightratio){
    $ratio = $widthratio;
   }else{
    $ratio = $heightratio;
   }
   $newwidth = $width * $ratio;
   $newheight = $height * $ratio;
  
   if(function_exists("imagecopyresampled")){
    $newim = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
   }else{
    $newim = imagecreate($newwidth, $newheight);
    imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
   }
   imagejpeg ($newim,$name . ".jpg");
   imagedestroy ($newim);
  }else{
   imagejpeg ($im,$name . ".jpg");
  }
 }

 if($_files['image']['size']){
  //echo $_files['image']['type'];
  if($_files['image']['type'] == "image/pjpeg"||$_files['image']['type'] == "image/jpg"||$_files['image']['type'] == "image/jpeg"){
   $im = imagecreatefromjpeg($_files['image']['tmp_name']);
  }elseif($_files['image']['type'] == "image/x-png"){
   $im = imagecreatefrompng($_files['image']['tmp_name']);
  }elseif($_files['image']['type'] == "image/gif"){
   $im = imagecreatefromgif($_files['image']['tmp_name']);
  }
  if($im){
   if(file_exists($pic_name.'.jpg')){
    unlink($pic_name.'.jpg');
   }
   resizeimage($im,$pic_width,$pic_height,$pic_name);
   imagedestroy ($im);
  }
 }
?>

<img src="<? echo $pic_name.'.jpg'; ?>"><br><br>
<form enctype="multipart/form-data" method="post" action="small_picture.php">
<br>
<input type="file" name="image" size="50" value="浏览"><p>
生成缩略图宽度:<input type="text" name="width" size="5"><p>
生成缩略图长度:<input type="text" name="length" size="5"><p>
<input type="submit" value="上传图片">
</form>

[!--infotagslink--]

相关文章

  • php二维码生成

    本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
  • Java生成随机姓名、性别和年龄的实现示例

    这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php生成唯一数字id的方法汇总

    关于生成唯一数字ID的问题,是不是需要使用rand生成一个随机数,然后去数据库查询是否有这个数呢?感觉这样的话有点费时间,有没有其他方法呢?当然不是,其实有两种方法可以解决。 1. 如果你只用php而不用数据库的话,那时间戳+随...2015-11-24
  • jQuery为动态生成的select元素添加事件的方法

    下面小编就为大家带来一篇jQuery为动态生成的select元素添加事件的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-09-01
  • PHP自动生成后台导航网址的最佳方法

    经常制作开发不同的网站的后台,写过很多种不同的后台导航写法。 最终积累了这种最写法,算是最好的吧...2013-09-29
  • js生成随机数的方法实例

    js生成随机数主要用到了内置的Math对象的random()方法。用法如:Math.random()。它返回的是一个 0 ~ 1 之间的随机数。有了这么一个方法,那生成任意随机数就好理解了。比如实际中我们可能会有如下的需要: (1)生成一个 0 - 1...2015-10-21
  • c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
  • PHP验证码生成与验证例子

    验证码是一个现在WEB2.0中常见的一个功能了,像注册、登录又或者是留言页面,都需要注册码来验证当前操作者的合法性,我们会看到有些网站没有验证码,但那是更高级的验证了,...2016-11-25
  • PHP生成不同颜色、不同大小的tag标签函数

    复制代码 代码如下:function getTagStyle(){ $minFontSize=8; //最小字体大小,可根据需要自行更改 $maxFontSize=18; //最大字体大小,可根据需要自行更改 return 'font-size:'.($minFontSize+lcg_value()*(abs($maxFo...2013-10-04
  • JS生成某个范围的随机数【四种情况详解】

    下面小编就为大家带来一篇JS生成某个范围的随机数【四种情况详解】。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧...2016-04-22
  • php中利用str_pad函数生成数字递增形式的产品编号

    解决办法:$str=”QB”.str_pad(($maxid[0]["max(id)"]+1),5,”0″,STR_PAD_LEFT ); 其中$maxid[0]["max(id)"]+1) 是利用max函数从数据库中找也ID最大的一个值, ID为主键,不会重复。 str_pad() 函数把字符串填充为指...2013-10-04
  • C#生成Word文档代码示例

    这篇文章主要介绍了C#生成Word文档代码示例,本文直接给出代码实例,需要的朋友可以参考下...2020-06-25
  • Vue组件文档生成工具库的方法

    本文主要介绍了Vue组件文档生成工具库的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-08-11
  • PHP简单实现生成txt文件到指定目录的方法

    这篇文章主要介绍了PHP简单实现生成txt文件到指定目录的方法,简单对比分析了PHP中fwrite及file_put_contents等函数的使用方法,需要的朋友可以参考下...2016-04-28
  • PHP批量生成图片缩略图(1/5)

    这款批量生成缩略图代码可以生成指定大小的小图哦,并且支持文件批量上传。 这款教程会用到php文件 view.php config.php funs.php index.php 功能: -------...2016-11-25
  • C#实现为一张大尺寸图片创建缩略图的方法

    这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
  • 史上最简洁C# 生成条形码图片思路及示例分享

    这篇文章主要介绍了史上最简洁C# 生成条形码图片思路及示例分享,需要的朋友可以参考下...2020-06-25
  • php 上传文件并生成缩略图代码

    if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
  • 简单入门级php 生成xml文档代码

    $doc = new domdocument('1.0'); // we want a nice output $doc->formatoutput = true; 代码如下 复制代码 $root = $doc->createelement('bo...2016-11-25