php 生成缩略图代码可自动填充空白处

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

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

 

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

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教程 大图生成缩略图实现代码

 

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

gd库是php教程中一个处理图像的专用库,他可以方便快捷的处理大多数据处理,它提供了大量的图片处理函数,下面我们就利用gd库的函数来生成缩略图。
测试代码

 

<?php
include('resizeimage.php');
if(!empty($_post)){
echo($filename.".jpg?cache=".rand(0,999999));
}
?>
<form name="test" action="?submit=true" enctype="multipart/form-data" method="post" >
<input type="file" name="image" size="50" value="浏览"><p>
<input type="submit" value="上传图片">
</form>

resizeimage.php 文件

<?php
$filename="image.thumb";
// 生成图片的宽度
$resizewidth=400;
// 生成图片的高度
$resizeheight=400;

function resizeimage($im,$maxwidth,$maxheight,$name){
$width = imagesx($im);
$height = imagesy($im);
if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
if($maxwidth && $width > $maxwidth){
$widthratio = $maxwidth/$width;
$resizewidth=true;
}
if($maxheight && $height > $maxheight){
$heightratio = $maxheight/$height;
$resizeheight=true;
}
if($resizewidth && $resizeheight){
if($widthratio < $heightratio){
$ratio = $widthratio;
}else{
$ratio = $heightratio;
}
}elseif($resizewidth){
$ratio = $widthratio;
}elseif($resizeheight){
$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']){
if($_files['image']['type'] == "image/pjpeg"){
$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("$filename.jpg")){
unlink("$filename.jpg");
}
resizeimage($im,$resizewidth,$resizeheight,$filename);
imagedestroy ($im);
}
}
?>

[!--infotagslink--]

相关文章

  • MyBatis-Plus自动填充功能失效导致的原因及解决

    这篇文章主要介绍了MyBatis-Plus自动填充功能失效导致的原因及解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
  • C#实现延时并自动关闭MessageBox的方法

    这篇文章主要介绍了C#实现延时并自动关闭MessageBox的方法,非常实用的功能,需要的朋友可以参考下...2020-06-25
  • c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
  • SpringMvc自动装箱及GET请求参数原理解析

    这篇文章主要介绍了SpringMvc自动装箱及GET请求参数原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-19
  • 利用Redis如何实现自动补全功能

    这篇文章主要给大家介绍了关于如何利用Redis如何实现自动补全功能的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Redis具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-04-17
  • PHP批量生成图片缩略图(1/5)

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

    这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
  • php 上传文件并生成缩略图代码

    if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
  • MySQL自动停机的问题处理实战记录

    这篇文章主要给大家介绍了关于MySQL自动停机的问题处理,文中通过示例代码介绍的非常详细,对大家学习或者使用MySQL具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-01
  • CentOS下编译安装nginx及配置缩略图插件的方法教程

    这篇文章主要给大家介绍了在CentOS系统下编译安装nginx及配置缩略图插件的方法教程,文中给出了详细的安装步骤,对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。...2017-07-06
  • Email URL的判断和自动转换函数

    <?php function validateEmail($email) { return eregi("^[_a-z0-9-] (.[_a-z0-9-] )*@[a-z0-9-] (.[a-z0-9-] )*(.[a-z]{2,3})$", $email); } function validat...2016-11-25
  • 类的自动加载

    当你尝试使用一个未定义的类时,PHP会报告一个致命错误. 解决方法就是添加一个类,可以用include包含一个文件. 究竟你知道要用到哪个类. 但是,PHP提供了类的自动加载功...2016-11-25
  • c#多图片上传并生成缩略图的实例代码

    今天写了一个上传多张图片并生成缩略图的小程序。当然因为是菜鸟,所以写的一般。但还是学到了不少东西。现在上代码。...2021-09-22
  • 实例:实现自动清除日期目录shell脚本

    这次文章给大家带来的是一个简单使用的实例:实现自动清除日期目录shell脚本,对脚本感兴趣的下面我们一起来看看那具体的清除日期方法。 实现自动清除日期目录shell...2017-07-06
  • Nginx配合php实现生成实时缩略图功能

    这篇文章主要介绍了Nginx配合php实现生成实时缩略图功能,这在一些特殊场合可能会要用到,需要的朋友可以参考下...2016-01-27
  • js通过canvas生成图片缩略图

    对于生成缩略图一般做法是通过后端语言php等来生成,但是为了给服务器减压,我们或许可以从前端来着手,先生成好不同尺寸的缩略图,传给后端,而后端只需要将前端传过来的图片进行存储就好了...2020-10-03
  • php 图片上传代码(具有生成缩略图与增加水印功能)

    这款图片上传源代码是一款可以上传图片并且还具有给上传的图片生成缩略图与增加水印功能哦,可以说是一款完美的图片上传类哦。 代码如下 复制代码 ...2016-11-25
  • 关闭PayPal预付款,避免自动扣费的教程

    PayPal在国外就是支付宝一样强大了许多的平台都支持PayPal付款了,我信如果购买国外主机肯定会用到PayPal了,今天我们来给各位介绍关闭PayPal预付款,避免自动扣费吧,具体如...2016-10-10
  • C# jpg缩略图函数代码

    生成jpg缩略图字节,本人的小软件中需要用到的功能,所以自己做了一个函数,和大家分享 为什么要生成字节而不是文件,这是为了方便后续处理啦^_^...2020-06-25
  • php支持生成缩略图文件上传代码

    <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1...2016-11-25