首页 > 编程技术 > php

php 随机显示图片的多种方法

发布时间:2016-11-25 16:57

<?
$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" width=100% src="<?=$array[$suiji]?>">

实例二

<?php
/**********************************************
* Filename : img.php
* Author : freemouse
* web : www.111cn.net * email :freemouse1981@gmail.com
* Date : 2010/12/27
* Usage:
* <img" width=100% src=img.php>
* <img" width=100% 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" width=100% src="<? echo $exstr[2];?>" width="200" height="50" alt="<? echo $exstr[0];?>" ></a>');


HTML文件
<html>
<body>
<script language='javascript'" width=100% 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" width=100% src=/images/banner/webjxcomad1.gif" alt="广告1"> </a>
  ################################
  display=10   
  <a href="广告2连接地址" target=_blank>
  <img" width=100% src=images/banner/webjxcomad2.gif" width="468" height="60" alt="广告2" border="0"></a> 

验证码在php中是经常会用到了,下面我们为你提供了一些关于php验证码生成类与程序,直接复制下去就可以直接用的哦,下面看代码。

验证码在php教程中是经常会用到了,下面我们为你提供了一些关于php验证码生成类与程序,直接复制下去就可以直接用的哦,下面看代码。

<?php
session_start();
Header("Content-type: image/gif");
class SecurityCode
{
private $codes = '';
function __construct()
{
$code = '0-1-2-3-4-5-6-7-8-9-A-B-C-D-E-F-G-H-I-J-K-L-M-N-O-P-Q-R-S-T-U-V-W-X-Y-Z';
$codeArray = explode('-',$code);
shuffle($codeArray);
$this->codes = implode('',array_slice($codeArray,0,4));
}
public function CreateImg()
{
$_SESSION['check_pic'] = $this->codes;
$img = imagecreate(70,25);
imagecolorallocate($img,222,222,222);
$testcolor1 = imagecolorallocate($img,255,0,0);
$testcolor2 = imagecolorallocate($img,51,51,51);
$testcolor3 = imagecolorallocate($img,0,0,255);
$testcolor4 = imagecolorallocate($img,255,0,255);
for ($i = 0; $i < 4; $i++)
{
imagestring($img,rand(5,6),8 + $i * 15,rand(2,8),$this->codes[$i],rand(1,4));
}
imagegif($img);
}
}
$code = new SecurityCode();
$code->CreateImg();
$code = NULL;
?>

代码二

 

<?
session_start();
for($i=0; $i<4; $i++){
$rand.= dechex(rand(1,15));
}
$_SESSION[check_pic]=$rand;
//echo $_SESSION[check_pic];
// 设置图片大小">图片大小
$im = imagecreatetruecolor(100,30);
// 设置颜色
$bg=imagecolorallocate($im,0,0,0);
$te=imagecolorallocate($im,255,255,255);
// 把字符串写在图像左上角
imagestring($im,rand(5,6),rand(25,30),5,$rand,$te);
// 输出图像
header("Content-type:image/jpeg");
imagejpeg($im);
?>

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

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

 

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

标签:[!--infotagslink--]

您可能感兴趣的文章: