php缩略图生成几种方法代码

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

1. 从中我们可以看到imagecreatetruecolor函数的作用明显地是创建一幅黑色的背景图片,它的第一个参数为所创建图片的宽,第二个参数为所创建图片的高,我们把这个函数的返回值(图像标识符)存入变量里面。

2.imagecreatefromjpeg作用就是将要进行分割的图片读到内存里面(这里大家可能有纪疑问:我直接从硬微盘里读不就得了,为什么还要先读到内存里呢?打个不恰当的比方,大家平时在用钱的时相信大家不会口袋里不会放太多,一般到用的时候才从银行里面取,这里也是一样,这张图片不用它的时候我把它放在硬盘里面,当要对这张图片进行分割或其它操作时就把它读到内存里面,说白了,内存给程序提供了一个运行的舞台)

3.再看imagecopyresampled函数它的作用是将原图片分割好,然后将它和采样拷贝(我理解为投影)到用imagecreatefromjpeg创建好的背景图片上。

<?php教程
// The file
$filename = 'temp/Sunset.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;

//以原图片的长宽的0.5为新的长宽来创建新的图片此图片的标志为$image_p
$image_p = imagecreatetruecolor($new_width, $new_height);
//从 JPEG文件或URL新建一图像
$image = imagecreatefromjpeg($filename);
//将原始图片从坐标(100,100)开始分割,分割的长度(400),高度为(300)原图片的一半,将分割好的图片放在从坐标(0,0)开始的已建好的区域里
imagecopyresampled($image_p, $image, 0, 0, 100, 100, $new_width, $new_height, 400, 300);

// Output
imagejpeg($image_p, null, 100);//quality为图片输出的质量范围从 0(最差质量,文件更小)到 100(最佳质量,文件最大)。
?>

上面的例子是把$image图片从坐标(100,100)进行分割,分割后的宽为400,高为300,然后再将此图片从坐标(0,0)处开始投影到图片$image_p上,,投影的宽为$new_width,高为$new_height。

 

<?php

// 文件及缩放尺寸
//$imgfile = 'smp.jpg';
//$percent = 0.2;
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
$newwidth = $width * $percent;
$newheight = $height * $percent;
$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = imagecreatefromjpeg($imgfile);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb);
?>

更详细教程

<?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);
}
?>

实例四

$thumbnail = new ImageResize();
$thumbnail->resizeimage(源图片完整路径, 缩略图宽度, 缩略图高度, 是否剪裁(0或者1), 新图片完整路径);

class ImageResize {
   
    //图片类型
    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);
        }
       
        if($this->type=="bmp") {
            $this->im = $this->imagecreatefrombmp($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;
    }
   
    function ConvertBMP2GD($src, $dest = false) {
        if(!($src_f = fopen($src, "rb"))) {
            return false;
        }
        if(!($dest_f = fopen($dest, "wb"))) {
            return false;
        }
        $header = unpack("vtype/Vsize/v2reserved/Voffset", fread($src_f,14));
        $info = unpack("Vsize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vncolor/Vimportant", fread($src_f, 40));
       
        extract($info);
        extract($header);
       
        if($type != 0x4D42) { // signature "BM"
            return false;
        }
       
        $palette_size = $offset - 54;
        $ncolor = $palette_size / 4;
        $gd_header = "";
        // true-color vs. palette
        $gd_header .= ($palette_size == 0) ? "xFFxFE" : "xFFxFF";
        $gd_header .= pack("n2", $width, $height);
        $gd_header .= ($palette_size == 0) ? "x01" : "x00";
        if($palette_size) {
            $gd_header .= pack("n", $ncolor);
        }
        // no transparency
        $gd_header .= "xFFxFFxFFxFF";

        fwrite($dest_f, $gd_header);

        if($palette_size) {
            $palette = fread($src_f, $palette_size);
            $gd_palette = "";
            $j = 0;
            while($j < $palette_size) {
                $b = $palette{$j++};
                $g = $palette{$j++};
                $r = $palette{$j++};
                $a = $palette{$j++};
                $gd_palette .= "$r$g$b$a";
            }
            $gd_palette .= str_repeat("x00x00x00x00", 256 - $ncolor);
            fwrite($dest_f, $gd_palette);
        }

        $scan_line_size = (($bits * $width) + 7) >> 3;
        $scan_line_align = ($scan_line_size & 0x03) ? 4 - ($scan_line_size &
        0x03) : 0;

        for($i = 0, $l = $height - 1; $i < $height; $i++, $l--) {
            // BMP stores scan lines starting from bottom
            fseek($src_f, $offset + (($scan_line_size + $scan_line_align) * $l));
            $scan_line = fread($src_f, $scan_line_size);
            if($bits == 24) {
                $gd_scan_line = "";
                $j = 0;
                while($j < $scan_line_size) {
                    $b = $scan_line{$j++};
                    $g = $scan_line{$j++};
                    $r = $scan_line{$j++};
                    $gd_scan_line .= "x00$r$g$b";
                }
            }
            else if($bits == 8) {
                $gd_scan_line = $scan_line;
            }
            else if($bits == 4) {
                $gd_scan_line = "";
                $j = 0;
                while($j < $scan_line_size) {
                    $byte = ord($scan_line{$j++});
                    $p1 = chr($byte >> 4);
                    $p2 = chr($byte & 0x0F);
                    $gd_scan_line .= "$p1$p2";
                }
                $gd_scan_line = substr($gd_scan_line, 0, $width);
            }
            else if($bits == 1) {
                $gd_scan_line = "";
                $j = 0;
                while($j < $scan_line_size) {
                    $byte = ord($scan_line{$j++});
                    $p1 = chr((int) (($byte & 0x80) != 0));
                    $p2 = chr((int) (($byte & 0x40) != 0));
                    $p3 = chr((int) (($byte & 0x20) != 0));
                    $p4 = chr((int) (($byte & 0x10) != 0));
                    $p5 = chr((int) (($byte & 0x08) != 0));
                    $p6 = chr((int) (($byte & 0x04) != 0));
                    $p7 = chr((int) (($byte & 0x02) != 0));
                    $p8 = chr((int) (($byte & 0x01) != 0));
                    $gd_scan_line .= "$p1$p2$p3$p4$p5$p6$p7$p8";
                }
                $gd_scan_line = substr($gd_scan_line, 0, $width);
            }
            fwrite($dest_f, $gd_scan_line);
        }
        fclose($src_f);
        fclose($dest_f);
        return true;
    }

    function imagecreatefrombmp($filename) {
        $tmp_name = tempnam("/tmp", "GD");
        if($this->ConvertBMP2GD($filename, $tmp_name)) {
            $img = imagecreatefromgd($tmp_name);
            unlink($tmp_name);
            return $img;
        }
        return false;
    }
   
}

<?
$handle = opendir('./'); //当前目录
while (false !== ($file = readdir($handle))) { //遍历该php教程文件所在目录
list($filesname,$kzm)=explode(".",$file);//获取扩展名
if ($kzm=="gif" or $kzm=="jpg") { //文件过滤
if (!is_dir('./'.$file)) {  //文件夹过滤
$array[]=$file;//把符合条件的文件名存入数组
}
}
}
$suiji=array_rand($array); //使用array_rand函数从数组中随机抽出一个单元
?>
<img src="<?=$array[$suiji]?>">

实例二

<?php
/**********************************************
* Filename : img.php
* Author : freemouse
* web : www.111cn.net * email :freemouse1981@gmail.com
* Date : 2010/12/27
* Usage:
* <img src=img.php>
* <img src=img.php?folder=images2/>
***********************************************/
if($_GET['folder']){
$folder=$_GET['folder'];
}else{
$folder='/images/';
}
//存放图片文件的位置
$path = $_SERVER['DOCUMENT_ROOT']."/".$folder;
$files=array();
if ($handle=opendir("$path")) {
while(false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(substr($file,-3)=='gif' || substr($file,-3)=='jpg') $files[count($files)] = $file;
}
}
}
closedir($handle);

$random=rand(0,count($files)-1);
if(substr($files[$random],-3)=='gif') header("Content-type: image/gif");
elseif(substr($files[$random],-3)=='jpg') header("Content-type: image/jpeg");
readfile("$path/$files[$random]");
?>


readrand.php(此程序实际上是生成一句网页特效语言)
<?
$arrayall=file("tp.txt");读出tp.txt内容到数组
$arrays=count($arrayall);
if ($arrays==1){//because rand(0,0) is wrong
$selectrand=0;
}else{
srand((double)microtime()*1000000);//设定随机数种子
$selectrand=rand(0,$arrays-1);
}
$exstr=explode(chr(9),$arrayall[$selectrand]);//从全部中随机取出一个并分割
?>
document.write('<a href="<? echo $exstr[1];?>" target="new"><img src="<? echo $exstr[2];?>" width="200" height="50" alt="<? echo $exstr[0];?>" ></a>');


HTML文件
<html>
<body>
<script language='javascript' src='readrand.php'>
</script>
</body>
</html>


(你可以把scripty放到你需要的位置,并可以加入setTimeout()函数以实现定时刷新)

随机广告代码

<?php
  #########随机广告显示##########
  function myads(){
  $dir="ads"; #设置存放记录的目录
  //$dir="ads"; #设置存放记录的目录
  $ads="$dir/ads.txt"; #设置广告代码文件
  $log ="$dir/ads.log"; #设置ip记录文件
  
  $ads_lines=file($ads);
  $lines=count($ads_lines);#文件总行数
  
  ####读出广告总数$ads_count和显示次数到数组$display_array########
  $ads_count=0;
  $display_count=0;
  for ($i=0;$i<$lines;$i++){
   if((!strcmp(substr($ads_lines[$i],0,7),"display"))){
   $ads_count+=1;
   $display_array[$ads_count]=substr($ads_lines[$i],8);
   $display_count+=$display_array[$ads_count];
   }
  }
  ####决定随机显示序号$display_rand#####
  srand((double)microtime()*1000000);
  $display_rand = rand(1,$display_count);
  
  ###决定广告序号$ads_num######
  $pricount=0;
  $ads_num=1;
  for($i=1; $i<=$ads_count; $i++) {
   $pricount += $display_array[$i];
   if ($display_rand<=$pricount) {$ads_num=$i;break;}
  }
  
  #####播放广告########
  $num=0;
  $flag=0;
  
  for($i=0;$i<$lines;$i++){
   if((!strcmp(substr($ads_lines[$i],0,7),"display"))){$num++;}
   if(($num==$ads_num)and($flag==0)){$flag=1;continue;}
   if(($flag==1)and strcmp($ads_lines[$i][0],"#")){echo $ads_lines[$i];continue;}
   if(($flag==1)and(!(strcmp($ads_lines[$i][0],"#")))){break;}
  }
  ####纪录广告显示次数#########
  $fp=fopen($log,"a");
  fputs($fp,date( "Y-m-d H:i:s " ).getenv("REMOTE_ADDR")."==>".$ads_num."n");
  fclose($fp);
  }
  ?>


广告代码文件ads.txt

以下为引用的内容:
  ########每个广告代码之间用'#'隔开,display为显示加权数,越大显示次数越多######
  display=10   
  <a href="广告1连接地址">
  <img src=/images/banner/webjxcomad1.gif" alt="广告1"> </a>
  ################################
  display=10   
  <a href="广告2连接地址" target=_blank>
  <img src=images/banner/webjxcomad2.gif" width="468" height="60" alt="广告2" border="0"></a> 

网站大多数生成缩略图都是按比例操作的,今天我们来看看可以固定图片大小">图片大小,不够的地方自动填充空白哦。有需要的朋友可以参考一下。

 

<?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;
}
?>

超简单php教程 大图生成缩略图实现代码

 

<?php
/**
* 生成缩略图
*
* @param string $imagepath 图片路径
* @param string $thumb 生成缩略图名称
* @param integer $width 生成缩略图最大宽度
* @param integer $height 生成缩略图最大高度
*

*/
function resizeimage($imagepath, $thumb, $width = 200, $height = 200)
{
    list($imagewidth, $imageheight) = getimagesize($imagepath);
    $imagepath = imagecreatefromjpeg($imagepath);
    if ($width && ($imagewidth < $imageheight))
    {
        $width = ($height / $imageheight) * $imagewidth;
    }
    else
    {
        $height = ($width / $imagewidth) * $imageheight;
    }
    $image = imagecreatetruecolor($width, $height);
    imagecopyresampled($image, $imagepath, 0, 0, 0, 0, $width, $height, $imagewidth, $imageheight);
    imagepng($image, $thumb);
    imagedestroy($image);
}
resizeimage('test.jpg', 'test_thumb.jpg');
?>

<?php教程
session_start();
header("content-type: image/png");
$str = "的一是在了不和有大这主中人上为们地个用工时要动国产以我到他会作来分生对于学下级就年阶义发成部民可出能方进同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批如应形想制心样干都向变关点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫康遵牧遭幅园腔订香肉弟屋敏恢忘衣孙龄岭骗休借丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩";
$imgwidth = 110;
$imgheight = 24;
$authimg = imagecreate($imgwidth,$imgheight);
$bgcolor = imagecolorallocate($authimg,255,255,255);
$fontfile = "wrzc_net.ttf";
$white=imagecolorallocate($authimg,234,185,95);
imagearc($authimg, 150, 8, 20, 20, 75, 170, $white);
imagearc($authimg, 100, 7,50, 22, 75, 175, $white);
imageline($authimg,20,20,180,30,$white);
imageline($authimg,20,18,170,50,$white);
imageline($authimg,25,50,80,50,$white);
$noise_num = 100;
$line_num = 5;
imagecolorallocate($authimg,0xff,0xff,0xff);
$rectangle_color=imagecolorallocate($authimg,0xaa,0xaa,0xaa);
$noise_color=imagecolorallocate($authimg,0x33,0x33,0x33);
$font_color=imagecolorallocate($authimg,0x00,0x00,0x00);
$line_color=imagecolorallocate($authimg,0x00,0x00,0x00);
for($i=0;$i<$noise_num;$i++){
 imagesetpixel($authimg,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$noise_color);
}
for($i=0;$i<$line_num;$i++){
 imageline($authimg,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$line_color);
}
$randnum=rand(0,strlen($str)-4);
if($randnum%2)$randnum+=1;
$str = substr($str,$randnum,8);
$_session['supdesverify'] = $str;
$str = iconv("gb2312","utf-8",$str);
imagettftext($authimg, 20, 0, 0, 21, $font_color, $fontfile, $str);
imagepng($authimg);
imagedestroy($authimg);
?>
[!--infotagslink--]

相关文章

  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • js识别uc浏览器的代码

    其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
  • JS实现双击屏幕滚动效果代码

    本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
  • JS日期加减,日期运算代码

    一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
  • PHP开发微信支付的代码分享

    微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
  • php二维码生成

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

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

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下:1.计算两个时间的相差几天$startdate=strtotime("2009-12-09");$enddate=strtotime("2009-12-05");上面的php时间日期函数strtotime已经把字符串...2015-11-24
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • php导出csv格式数据并将数字转换成文本的思路以及代码分享

    php导出csv格式数据实现:先定义一个字符串 存储内容,例如 $exportdata = '规则111,规则222,审222,规222,服2222,规则1,规则2,规则3,匹配字符,设置时间,有效期'."/n";然后对需要保存csv的数组进行foreach循环,例如复制代...2014-06-07
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13