php生成雪花背景验证码程序代码

 更新时间:2016年11月25日 16:56  点击:1858
本文章来给大家介绍php生成雪花背景验证码程序代码 ,有需要的朋友可进入参考参考。

验证码生成程序

 代码如下 复制代码

<?php
session_start();
session_register("login_check_number");
//昨晚看到了chianren上的验证码效果,就考虑了一下,用PHP的GD库完成了类似功能
//先成生背景,再把生成的验证码放上去
$img_height=120;    //先定义图片的长、宽
$img_width=40;
if($HTTP_GET_VARS["act"]== "init"){
    //srand(microtime() * 100000);//PHP420后,srand不是必须的
    for($Tmpa=0;$Tmpa<4;$Tmpa++){
        $nmsg.=dechex(rand(0,15));
    }//by sports98


    $HTTP_SESSION_VARS[login_check_number] = $nmsg;

    //$HTTP_SESSION_VARS[login_check_number] = strval(mt_rand("1111","9999"));    //生成4位的随机数,放入session中
    //谁能做下补充,可以同时生成字母和数字啊??----由sports98完成了

    $aimg = imageCreate($img_height,$img_width);    //生成图片
    ImageColorAllocate($aimg, 255,255,255);            //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了
    $black = ImageColorAllocate($aimg, 0,0,0);        //定义需要的黑色
    ImageRectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//先成一黑色的矩形把图片包围

    //下面该生成雪花背景了,其实就是在图片上生成一些符号
    for ($i=1; $i<=100; $i++) {    //先用100个做测试
        imageString($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"*",imageColorAllocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
        //哈,看到了吧,其实也不是雪花,就是生成*号而已。为了使它们看起来"杂乱无章、5颜6色",就得在1个1个生成它们的时候,让它们的位置、颜色,甚至大小都用随机数,rand()或mt_rand都可以完成。
    }

    //上面生成了背景,现在就该把已经生成的随机数放上来了。道理和上面差不多,随机数1个1个地放,同时让他们的位置、大小、颜色都用成随机数~~
    //为了区别于背景,这里的颜色不超过200,上面的不小于200
    for ($i=0;$i<strlen($HTTP_SESSION_VARS[login_check_number]);$i++){
        imageString($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(1,10),mt_rand(1,$img_width/2), $HTTP_SESSION_VARS[login_check_number][$i],imageColorAllocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));
    }
    Header("Content-type: image/png");    //告诉浏览器,下面的数据是图片,而不要按文字显示
    ImagePng($aimg);                    //生成png格式。
    ImageDestroy($aimg);
}
?>

验证测试页面

 代码如下 复制代码

<?session_start();?>
<FORM METHOD=POST ACTION="">
<input type=text name=number maxlength=4><img src="YanZhengMa.php?act=init">
<INPUT TYPE="submit" name="sub">
</FORM>
<?
//检验校验码
if(isset($HTTP_POST_VARS["sub"])):
if($HTTP_POST_VARS["number"] != $HTTP_SESSION_VARS[login_check_number] || empty($HTTP_POST_VARS["number"])){
    echo "校验码不正确!" ;
}else{
    echo"验证码通过!";
}
endif;
show_source('test.php');
//以上本页的源码


//以下是生成验证码的源码
show_source('YanZhengMa.php');
?>

图像添加水印在php中有很多种办法可以实现,他这些功能都是基于php中的GD库的,如果没有开户GD库是不可以使用水印功能的。

imagecopymerge() 函数用于拷贝并合并图像的一部分,成功返回 TRUE ,否则返回 FALSE 。

Windows下开启PHP的GD库支持

找到php.ini,打开内容,找到:

;extension=php_gd2.dll

把最前面的分号“;”去掉,再保存即可,如果本来就没有分号,那就是已经开启了

基本的语法

bool imagecopymerge( resource dst_im, resource src_im, int dst_x,
int dst_y, int src_x, int src_y, int src_w, int src_h, int pct )

参数说明: 参数 说明

dst_im 目标图像
src_im 被拷贝的源图像
dst_x 目标图像开始 x 坐标
dst_y 目标图像开始 y 坐标,x,y同为 0 则从左上角开始
src_x 拷贝图像开始 x 坐标
src_y 拷贝图像开始 y 坐标,x,y同为 0 则从左上角开始拷贝
src_w (从 src_x 开始)拷贝的宽度
src_h (从 src_y 开始)拷贝的高度
pct 图像合并程度,取值 0-100 ,当 pct=0 时,实际上什么也没做,反之完全合并。

当为 pct = 100 时对于调色板图像本函数和 imagecopy() 完全一样

知道了用法,要实现我们的功能就简单了,用下面的代码就可以轻松实现

 代码如下 复制代码

<?php
header("Content-type: image/jpeg");

//原始图像
$dst = "images/flower_1.jpg";

//得到原始图片信息
$dst_im = imagecreatefromjpeg($dst);
$dst_info = getimagesize($dst);

//水印图像
$src = "images/logo.gif";
$src_im = imagecreatefromgif($src);
$src_info = getimagesize($src);

//水印透明度
$alpha = 30;

//合并水印图片
imagecopymerge($dst_im,$src_im,$dst_info[0]-$src_info[0],$dst_info[1]-$src_info[1],0,0,$src_info[0],
$src_info[1],$alpha);

//输出合并后水印图片
imagejpeg($dst_im);
imagedestroy($dst_im);
imagedestroy($src_im);
?>

新版本之后imagecopymerge函数几乎不使用了,我们可直接使用imagecopy来生成水印两个函数的功能是完全一样的。

//增加水印
$watermark   =1;
$watertype   =2;
$waterstring =''; 
$waterimg="z.png";    //水印图片
$sFilePath ='aa.jpg';
if($watermark==1)
{
 $image_size = getimagesize($sFilePath); //上传的图片
 $water_size = getimagesize($waterimg);  //水印图片
 $iinfo=getimagesize($sFilePath,$iinfo);
 $nimage=imagecreatetruecolor($image_size[0],$image_size[1]);
 $white=imagecolorallocate($nimage,255,255,255);
 $black=imagecolorallocate($nimage,0,0,0);
 $red=imagecolorallocate($nimage,255,0,0);
 imagefill($nimage,0,0,$white);
 switch ($iinfo[2])
 {
  case 1:
   $simage =imagecreatefromgif($sFilePath);
   break;
  case 2:
   $simage =imagecreatefromjpeg($sFilePath);
   break;
  case 3:
   $simage =imagecreatefrompng($sFilePath);
   break;
//            case 6:
//            $simage =imagecreatefromwbmp($sFilePath);
//            break;
  default:
   die("不支持的文件类型");
   exit;
 }
 
 imagecopy($nimage,$simage,0,0,0,0,$image_size[0],$image_size[1]);
 
 switch($watertype)
 {
  case 1:   //加水印字符串
   imagestring($nimage,2,3,$image_size[1]-15,$waterstring,$black);
   break;
  case 2:   //加水印图片
   $simage1 =imagecreatefrompng($waterimg);     
   $x= $image_size[0]-$water_size[0];
   $y= $image_size[1]-$water_size[1];
   imagecopy($nimage,$simage1,$x,$y,0,0,240,65);
   imagedestroy($simage1);
   break;
 }
    
 switch ($iinfo[2])
 {
  case 1:
   imagegif($nimage, $sFilePath);
//            imagejpeg($nimage, $sFilePath);
   break;
  case 2:
   imagejpeg($nimage, $sFilePath);
   break;
  case 3:
   imagepng($nimage, $sFilePath);
   break;
//            case 6:
//            imagewbmp($nimage, $sFilePath);
//            //imagejpeg($nimage, $sFilePath);
//            break;
 }
 
 //覆盖原上传文件
 imagedestroy($nimage);
 imagedestroy($simage);
}

一个更好的功能,可以生成缩略并且还可以给图片添加水印


/***
 想操作图片
 先得把图片的大小,类型信息得到
 
 水印:就是把指定的水印复制到目标上,并加透明效果
 
 缩略图:就是把大图片复制到小尺寸画面上
 ***/  
 

 代码如下 复制代码

class ImageTool { 
    // imageInfo 分析图片的信息 
    // return array() 
    public static function imageInfo($image) { 
        // 判断图片是否存在 
        if (!file_exists($image)) { 
            return false; 
        } 
 
        $info = getimagesize($image); 
 
        if ($info == false) { 
            return false; 
        } 
 
        // 此时info分析出来,是一个数组 
        $img['width'] = $info[0]; 
        $img['height'] = $info[1]; 
        $img['ext'] = substr($info['mime'], strpos($info['mime'], '/') + 1); 
 
        return $img; 
    } 
 
    /*
     加水印功能
     parm String $dst 等操作图片
     parm String $water 水印小图
     parm String $save,不填则默认替换原始图
     */ 
    public static function water($dst, $water, $save = NULL, $pos = 2, $alpha = 50) { 
        // 先保证2个图片存在 
        if (!file_exists($dst) || !file_exists($water)) { 
            return false; 
        } 
 
        // 首先保证水印不能比待操作图片还大 
        $dinfo = self::imageInfo($dst); 
        $winfo = self::imageInfo($water); 
 
        if ($winfo['height'] > $dinfo['height'] || $winfo['width'] > $dinfo['width']) { 
            return false; 
        } 
 
        // 两张图,读到画布上! 但是图片可能是png,可能是jpeg,用什么函数读? 
        $dfunc = 'imagecreatefrom' . $dinfo['ext']; 
        $wfunc = 'imagecreatefrom' . $winfo['ext']; 
 
        if (!function_exists($dfunc) || !function_exists($wfunc)) { 
            return false; 
        } 
 
        // 动态加载函数来创建画布 
        $dim = $dfunc($dst); 
        // 创建待操作的画布 
        $wim = $wfunc($water); 
        // 创建水印画布 
 
        // 根据水印的位置 计算粘贴的坐标 
        switch($pos) { 
            case 0 : 
                // 左上角 
                $posx = 0; 
                $posy = 0; 
                break; 
 
            case 1 : 
                // 右上角 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = 0; 
                break; 
 
            case 3 : 
                // 左下角 
                $posx = 0; 
                $posy = $dinfo['height'] - $winfo['height']; 
                break; 
 
            default : 
                $posx = $dinfo['width'] - $winfo['width']; 
                $posy = $dinfo['height'] - $winfo['height']; 
        } 
 
        // 加水印 
        imagecopymerge($dim, $wim, $posx, $posy, 0, 0, $winfo['width'], $winfo['height'], $alpha); 
 
        // 保存 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
            // 删除原图 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($dim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($wim); 
 
        return true; 
    } 
 
    /**
     thumb 生成缩略图
     等比例缩放,两边留白
     **/ 
    public static function thumb($dst, $save = NULL, $width = 200, $height = 200) { 
        // 首先判断待处理的图片存不存在 
        $dinfo = self::imageInfo($dst); 
        if ($dinfo == false) { 
            return false; 
        } 
 
        // 计算缩放比例 
        $calc = min($width / $dinfo['width'], $height / $dinfo['height']); 
 
        // 创建原始图的画布 
        $dfunc = 'imagecreatefrom' . $dinfo['ext']; 
        $dim = $dfunc($dst); 
 
        // 创建缩略画布 
        $tim = imagecreatetruecolor($width, $height); 
 
        // 创建白色填充缩略画布 
        $white = imagecolorallocate($tim, 255, 255, 255); 
 
        // 填充缩略画布 
        imagefill($tim, 0, 0, $white); 
 
        // 复制并缩略 
        $dwidth = (int)$dinfo['width'] * $calc; 
        $dheight = (int)$dinfo['height'] * $calc; 
 
        $paddingx = (int)($width - $dwidth) / 2; 
        $paddingy = (int)($height - $dheight) / 2; 
 
        imagecopyresampled($tim, $dim, $paddingx, $paddingy, 0, 0, $dwidth, $dheight, $dinfo['width'],

$dinfo['height']); 
 
        // 保存图片 
        if (!$save) { 
            $save = $dst; 
            unlink($dst); 
        } 
 
        $createfunc = 'image' . $dinfo['ext']; 
        $createfunc($tim, $save); 
 
        imagedestroy($dim); 
        imagedestroy($tim); 
 
        return true; 
 
    } 
 

本文章给大家介绍一个非常不错的生成验证码的php程序,首先当用户请求HTTP的时候,服务器端就创建一个唯一的sessionid,这个是session会话ID,然后就去启动GD库或者imagemagick这些画图工具,把程序生成的随机的字符写到一张图片里面,然后显示到客户端,再由用户输入提交数据,然后我们程序把生成验证保存在session中进行比较,这样就完成了验证码的生成与验证了。

•新建一个PHP文件captcha_code_file.php

 代码如下 复制代码

//首先开启session
session_start();
//定义前台显示验证码长&宽
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';

//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
//定义要生成验证码的字符串
$code = '';

$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}

$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);

/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);

$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'],
        $arr_text_color['green'], $arr_text_color['blue']);

$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'],
        $arr_noice_color['green'], $arr_noice_color['blue']);

/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}

/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}

/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);

/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
//设置session,做验证
$_SESSION['6_letters_code'] = $code;

function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}

调用页面显示验证码页面index.php

 代码如下 复制代码

<?php
session_start();
if(isset($_REQUEST['Submit'])){
    // code for check server side validation
    if(empty($_SESSION['6_letters_code'] ) ||
        strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    { 
        $msg="您输入的验证码有误,请重新输入!";
    }else{
        echo "您输入的是正确的!";
        // Captcha verification is Correct. Final Code Execute here!
    }
}   
 ?>

<style type="text/css">
.table{
    font-family:Arial, Helvetica, sans-serif;
    font-size:12px;
    color:#333;
    background-color:#E4E4E4;   
}
.table td{
    background-color:#F8F8F8;   
}
</style>

<form action="" method="post" name="form1" id="form1" >
  <table width="400" border="0" align="center" cellpadding="5" cellspacing="1">
<?php if(isset($msg)){?>
    <tr>
      <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
    </tr>
<?php } ?>
    <tr>
      <td align="right" valign="top"> 验证码Demo:</td>
      <td><img src="captcha_code_file.php?rand=<?php echo rand(0,20);?>" id='captchaimg'  onclick="refreshCaptcha();" ><br>
        <label for='message'>请输入验证码:</label>
        <br>
        <input id="6_letters_code" name="6_letters_code" type="text">
        <br>
        如果看不到,请 <a href='javascript: refreshCaptcha();'>点我</a> 刷新一下!
        </p></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><input name="Submit" type="submit" onclick="return validate();" value="Submit"></td>
    </tr>
  </table>
</form>
<script type='text/javascript'>
//定义的刷新请求
function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>

一个简单的使用php上传图片文件生然后再生成一张等比例的缩略图效果,有需要学习的朋友可参考参考。
 代码如下 复制代码

 

<?php
function _UPLOADPIC($upfile, $maxsize, $updir, $newname = 'date') {

if ($newname == 'date')

$newname = date ( "Ymdhis" ); //使用日期做文件名 

$name = $upfile ["name"];

$type = $upfile ["type"];

$size = $upfile ["size"];

$tmp_name = $upfile ["tmp_name"];

switch ($type) {

case 'image/pjpeg' :

case 'image/jpeg' :

$extend = ".jpg";

break;

case 'image/gif' :

$extend = ".gif";

break;

case 'image/png' :

$extend = ".png";

break;

}

if (emptyempty ( $extend )) {

echo ( "警告!只能上传图片类型:GIF JPG PNG" );

exit ();

}

if ($size > $maxsize) {

$maxpr = $maxsize / 1000;

echo ( "警告!上传图片大小不能超过" . $maxpr . "K!" );

exit ();

}

if (move_uploaded_file ( $tmp_name, $updir . $newname . $extend )) {

return $updir . $newname . $extend;

}

}

 

function show_pic_scal($width, $height, $picpath) {

$imginfo = GetImageSize ( $picpath );

$imgw = $imginfo [0];

$imgh = $imginfo [1];

 

$ra = number_format ( ($imgw / $imgh), 1 ); //宽高比

$ra2 = number_format ( ($imgh / $imgw), 1 ); //高宽比

 

 

if ($imgw > $width or $imgh > $height) {

if ($imgw > $imgh) {

$newWidth = $width;

$newHeight = round ( $newWidth / $ra );

 

} elseif ($imgw < $imgh) {

$newHeight = $height;

$newWidth = round ( $newHeight / $ra2 );

} else {

$newWidth = $width;

$newHeight = round ( $newWidth / $ra );

}

} else {

$newHeight = $imgh;

$newWidth = $imgw;

}

$newsize [0] = $newWidth;

$newsize [1] = $newHeight;

 

return $newsize;

}

 

 

 

function getImageInfo($src)

{

return getimagesize($src);

}

/**

* 创建图片,返回资源类型

* @param string $src 图片路径

* @return resource $im 返回资源类型 

* **/ 

function create($src)

{

$info=getImageInfo($src);

switch ($info[2])

{

case 1:

$im=imagecreatefromgif($src);

break;

case 2:

$im=imagecreatefromjpeg($src);

break;

case 3:

$im=imagecreatefrompng($src);

break;

}

return $im;

}

/**

* 缩略图主函数

* @param string $src 图片路径

* @param int $w 缩略图宽度

* @param int $h 缩略图高度

* @return mixed 返回缩略图路径

* **/ 

 

function resize($src,$w,$h)

{

$temp=pathinfo($src);

$name=$temp["basename"];//文件名

$dir=$temp["dirname"];//文件所在的文件夹

$extension=$temp["extension"];//文件扩展名

$savepath="{$dir}/{$name}";//缩略图保存路径,新的文件名为*.thumb.jpg

 

//获取图片的基本信息

$info=getImageInfo($src);

$width=$info[0];//获取图片宽度

$height=$info[1];//获取图片高度

$per1=round($width/$height,2);//计算原图长宽比

$per2=round($w/$h,2);//计算缩略图长宽比

 

//计算缩放比例

if($per1>$per2||$per1==$per2)

{

//原图长宽比大于或者等于缩略图长宽比,则按照宽度优先

$per=$w/$width;

}

if($per1<$per2)

{

//原图长宽比小于缩略图长宽比,则按照高度优先

$per=$h/$height;

}

$temp_w=intval($width*$per);//计算原图缩放后的宽度

$temp_h=intval($height*$per);//计算原图缩放后的高度

$temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布

$im=create($src);

imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);

if($per1>$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return addBg($savepath,$w,$h,"w");

//宽度优先,在缩放之后高度不足的情况下补上背景

}

if($per1==$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return $savepath;

//等比缩放

}

if($per1<$per2)

{

imagejpeg($temp_img,$savepath, 100);

imagedestroy($im);

return addBg($savepath,$w,$h,"h");

//高度优先,在缩放之后宽度不足的情况下补上背景

}

}

/**

* 添加背景

* @param string $src 图片路径

* @param int $w 背景图像宽度

* @param int $h 背景图像高度

* @param String $first 决定图像最终位置的,w 宽度优先 h 高度优先 wh:等比

* @return 返回加上背景的图片

* **/ 

function addBg($src,$w,$h,$fisrt="w")

{

$bg=imagecreatetruecolor($w,$h);

$white = imagecolorallocate($bg,255,255,255);

imagefill($bg,0,0,$white);//填充背景

 

//获取目标图片信息

$info=getImageInfo($src);

$width=$info[0];//目标图片宽度

$height=$info[1];//目标图片高度

$img=create($src);

if($fisrt=="wh")

{

//等比缩放

return $src;

}

else 

{

if($fisrt=="w")

{

$x=0;

$y=($h-$height)/2;//垂直居中

}

if($fisrt=="h")

{

$x=($w-$width)/2;//水平居中

$y=0;

}

imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);

imagejpeg($bg,$src,100);

imagedestroy($bg);

imagedestroy($img);

return $src;

}
}
?> 

使用方法: 

$filename=(_UPLOADPIC($_FILES["upload"],$maxsize,$updir,$newname='date'));
$show_pic_scal=show_pic_scal(230, 230, $filename);
resize($filename,$show_pic_scal[0],$show_pic_scal[1]);

缩略图用得最多的是我们上传图片时生成一张小图,这样就可以很好的解决图片大小或影响网站整体美观的问题了,下面介绍的生成图片缩略图类都不支持图片上传,我们要先上传再调用此类来操作。

//使用如下类就可以生成图片缩略图,

 代码如下 复制代码

<?php
class resizeimage
{
    //图片类型
    var $type;
    //实际宽度
    var $width;
    //实际高度
    var $height;
    //改变后的宽度
    var $resize_width;
    //改变后的高度
    var $resize_height;
    //是否裁图
    var $cut;
    //源图象
    var $srcimg;
    //目标图象地址
    var $dstimg;
    //临时创建的图象
    var $im;

    function resizeimage($img, $wid, $hei,$c,$dstpath)
    {
        $this->srcimg = $img;
        $this->resize_width = $wid;
        $this->resize_height = $hei;
        $this->cut = $c;
        //图片的类型
  
$this->type = strtolower(substr(strrchr($this->srcimg,"."),1));

        //初始化图象
        $this->initi_img();
        //目标图象地址
        $this -> dst_img($dstpath);
        //--
        $this->width = imagesx($this->im);
        $this->height = imagesy($this->im);
        //生成图象
        $this->newimg();
        ImageDestroy ($this->im);
    }
    function newimg()
    {
        //改变后的图象的比例
        $resize_ratio = ($this->resize_width)/($this->resize_height);
        //实际图象的比例
        $ratio = ($this->width)/($this->height);
        if(($this->cut)=="1")
        //裁图
        {
            if($ratio>=$resize_ratio)
            //高度优先
            {
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width,$this-

>resize_height, (($this->height)*$resize_ratio), $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
            if($ratio<$resize_ratio)
            //宽度优先
            {
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, $this-

>resize_height, $this->width, (($this->width)/$resize_ratio));
                ImageJpeg ($newimg,$this->dstimg);
            }
        }
        else
        //不裁图
        {
            if($ratio>=$resize_ratio)
            {
                $newimg = imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, ($this-

>resize_width)/$ratio, $this->width, $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
            if($ratio<$resize_ratio)
            {
                $newimg = imagecreatetruecolor(($this->resize_height)*$ratio,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, ($this->resize_height)*$ratio,

$this->resize_height, $this->width, $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
        }
    }
    //初始化图象
    function initi_img()
    {
        if($this->type=="jpg")
        {
            $this->im = imagecreatefromjpeg($this->srcimg);
        }
        if($this->type=="gif")
        {
            $this->im = imagecreatefromgif($this->srcimg);
        }
        if($this->type=="png")
        {
            $this->im = imagecreatefrompng($this->srcimg);
        }
    }
    //图象目标地址
    function dst_img($dstpath)
    {
        $full_length  = strlen($this->srcimg);

        $type_length  = strlen($this->type);
        $name_length  = $full_length-$type_length;


        $name         = substr($this->srcimg,0,$name_length-1);
        $this->dstimg = $dstpath;


//echo $this->dstimg;
    }
}
?>

类的调用方法

$resizeimage = new resizeimage("图片源文件地址", "200", "100", "0","缩略图地址");

//就只用上面的一句话,就能生成缩略图,其中,源文件和缩略图地址可以相同,200,100分别代表宽和高

实例2

PHP缩略图 等比例无损压缩,可填充空白区域补充色

 代码如下 复制代码

<?php
error_reporting( E_ALL );

// 测试
imagezoom('1.jpg', '2.jpg', 400, 300, '#FFFFFF');

/*
    php缩略图函数:
        等比例无损压缩,可填充补充色 author: 华仔
    主持格式:
        bmp 、jpg 、gif、png
    param:
        @srcimage : 要缩小的图片
        @dstimage : 要保存的图片
        @dst_width: 缩小宽
        @dst_height: 缩小高
        @backgroundcolor: 补充色  如:#FFFFFF  支持 6位  不支持3位
*/
function imagezoom( $srcimage, $dstimage,  $dst_width, $dst_height, $backgroundcolor ) {
       
        // 中文件名乱码
        if ( PHP_OS == 'WINNT' ) {
                $srcimage = iconv('UTF-8', 'GBK', $srcimage);
                $dstimage = iconv('UTF-8', 'GBK', $dstimage);
        }
   
    $dstimg = imagecreatetruecolor( $dst_width, $dst_height );
    $color = imagecolorallocate($dstimg
        , hexdec(substr($backgroundcolor, 1, 2))
        , hexdec(substr($backgroundcolor, 3, 2))
        , hexdec(substr($backgroundcolor, 5, 2))
    );
    imagefill($dstimg, 0, 0, $color);
   
    if ( !$arr=getimagesize($srcimage) ) {
                echo "要生成缩略图的文件不存在";
                exit;
        }
       
    $src_width = $arr[0];
    $src_height = $arr[1];
    $srcimg = null;
    $method = getcreatemethod( $srcimage );
    if ( $method ) {
        eval( '$srcimg = ' . $method . ';' );
    }
   
    $dst_x = 0;
    $dst_y = 0;
    $dst_w = $dst_width;
    $dst_h = $dst_height;
    if ( ($dst_width / $dst_height - $src_width / $src_height) > 0 ) {
        $dst_w = $src_width * ( $dst_height / $src_height );
        $dst_x = ( $dst_width - $dst_w ) / 2;
    } elseif ( ($dst_width / $dst_height - $src_width / $src_height) < 0 ) {
        $dst_h = $src_height * ( $dst_width / $src_width );
        $dst_y = ( $dst_height - $dst_h ) / 2;
    }

    imagecopyresampled($dstimg, $srcimg, $dst_x
        , $dst_y, 0, 0, $dst_w, $dst_h, $src_width, $src_height);
   
    // 保存格式
    $arr = array(
        'jpg' => 'imagejpeg'
        , 'jpeg' => 'imagejpeg'
        , 'png' => 'imagepng'
        , 'gif' => 'imagegif'
        , 'bmp' => 'imagebmp'
    );
    $suffix = strtolower( array_pop(explode('.', $dstimage ) ) );
    if (!in_array($suffix, array_keys($arr)) ) {
        echo "保存的文件名错误";
        exit;
    } else {
        eval( $arr[$suffix] . '($dstimg, "'.$dstimage.'");' );
    }
   
    imagejpeg($dstimg, $dstimage);
   
    imagedestroy($dstimg);
    imagedestroy($srcimg);
   
}


function getcreatemethod( $file ) {
        $arr = array(
                '474946' => "imagecreatefromgif('$file')"
                , 'FFD8FF' => "imagecreatefromjpeg('$file')"
                , '424D' => "imagecreatefrombmp('$file')"
                , '89504E' => "imagecreatefrompng('$file')"
        );
        $fd = fopen( $file, "rb" );
        $data = fread( $fd, 3 );
       
        $data = str2hex( $data );
       
        if ( array_key_exists( $data, $arr ) ) {
                return $arr[$data];
        } elseif ( array_key_exists( substr($data, 0, 4), $arr ) ) {
                return $arr[substr($data, 0, 4)];
        } else {
                return false;
        }
}

function str2hex( $str ) {
        $ret = "";
       
        for( $i = 0; $i < strlen( $str ) ; $i++ ) {
                $ret .= ord($str[$i]) >= 16 ? strval( dechex( ord($str[$i]) ) )
                        : '0'. strval( dechex( ord($str[$i]) ) );
        }
       
        return strtoupper( $ret );
}

// BMP 创建函数  php本身无
function imagecreatefrombmp($filename)
{
   if (! $f1 = fopen($filename,"rb")) return FALSE;

   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;
  
   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
    $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }
  
   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
        $X=0;
        while ($X < $BMP['width'])
        {
         if ($BMP['bits_per_pixel'] == 24)
            $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
         elseif ($BMP['bits_per_pixel'] == 16)
         { 
            $COLOR = unpack("n",substr($IMG,$P,2));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 8)
         { 
            $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 4)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         elseif ($BMP['bits_per_pixel'] == 1)
         {
            $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
            if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
            elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
            elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
            elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
            elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
            elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
            elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
            elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
            $COLOR[1] = $PALETTE[$COLOR[1]+1];
         }
         else
            return FALSE;
         imagesetpixel($res,$X,$Y,$COLOR[1]);
         $X++;
         $P += $BMP['bytes_per_pixel'];
        }
        $Y--;
        $P+=$BMP['decal'];
   }
   fclose($f1);

return $res;
}
// BMP 保存函数,php本身无
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;
           
    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;
           
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;
           
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
           
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));
           
    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}

?>

总结,第一个类文件不如第二个好,因为第一个生成图之后图片会有点变模糊哦,后面这个生成类是高质量的。

[!--infotagslink--]

相关文章

  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • C#使用Process类调用外部exe程序

    本文通过两个示例讲解了一下Process类调用外部应用程序的基本用法,并简单讲解了StartInfo属性,有需要的朋友可以参考一下。...2020-06-25
  • 微信小程序 页面传值详解

    这篇文章主要介绍了微信小程序 页面传值详解的相关资料,需要的朋友可以参考下...2017-03-13
  • PHP 验证码不显示只有一个小红叉的解决方法

    最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04
  • 使用GruntJS构建Web程序之构建篇

    大概有如下步骤 新建项目Bejs 新建文件package.json 新建文件Gruntfile.js 命令行执行grunt任务 一、新建项目Bejs源码放在src下,该目录有两个js文件,selector.js和ajax.js。编译后代码放在dest,这个grunt会...2014-06-07
  • uniapp微信小程序:key失效的解决方法

    这篇文章主要介绍了uniapp微信小程序:key失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
  • jQuery Real Person验证码插件防止表单自动提交

    本文介绍的jQuery插件有点特殊,防自动提交表单的验证工具,就是我们经常用到的验证码工具,先给大家看看效果。效果图如下: 使用说明 需要使用jQuery库文件和Real Person库文件 同时需要自定义验证码显示的CSS样式 使用实例...2015-11-08
  • JS实现随机生成验证码

    这篇文章主要为大家详细介绍了JS实现随机生成验证码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-06
  • PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • 将c#编写的程序打包成应用程序的实现步骤分享(安装,卸载) 图文

    时常会写用c#一些程序,但如何将他们和photoshop一样的大型软件打成一个压缩包,以便于发布....2020-06-25
  • 微信小程序自定义tabbar组件

    这篇文章主要为大家详细介绍了微信小程序自定义tabbar组件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-03-14
  • 微信小程序 网络请求(GET请求)详解

    这篇文章主要介绍了微信小程序 网络请求(GET请求)详解的相关资料,需要的朋友可以参考下...2016-11-22
  • 微信小程序如何获取图片宽度与高度

    这篇文章主要给大家介绍了关于微信小程序如何获取图片宽度与高度的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-10
  • 微信小程序二维码生成工具 weapp-qrcode详解

    这篇文章主要介绍了微信小程序 二维码生成工具 weapp-qrcode详解,教大家如何在项目中引入weapp-qrcode.js文件,通过实例代码给大家介绍的非常详细,需要的朋友可以参考下...2021-10-23
  • Jquery插件实现点击获取验证码后60秒内禁止重新获取

    通过jquery.cookie.js插件可以快速实现“点击获取验证码后60秒内禁止重新获取(防刷新)”的功能效果图:先到官网(http://plugins.jquery.com/cookie/)下载cookie插件,放到相应文件夹,代码如下:复制代码 代码如下: <!DOCTYPE ht...2015-03-15
  • Python爬取微信小程序通用方法代码实例详解

    这篇文章主要介绍了Python爬取微信小程序通用方法代码实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-29
  • 微信小程序(应用号)开发新闻客户端实例

    这篇文章主要介绍了微信小程序(应用号)开发新闻客户端实例的相关资料,需要的朋友可以参考下...2016-10-25
  • php实现点击可刷新验证码

    验证码类文件 CreateImg.class.php <&#63;php class ValidationCode { private $width,$height,$codenum; public $checkcode; //产生的验证码 private $checkimage; //验证码图片 private $disturbColor = ''; /...2015-11-08