如何实现asp无组件生成缩略图
php生成图片缩略图的方法

php生成图片缩略图的方法php生成图片缩略图的方法虽然在HTML中可以通过指定图片的宽度和高度来随意缩放图片,但是这种方法不会减少图片的像素数目。
图形文件的尺寸没有改变,当然也不会加快图片下载的速度了。
当然也可以手动通过图形软件生成图片的缩略图,但对于大量的图片展示来说,这个工作量将十分巨大。
为此微缩图的自动生成程序就被设计出来了。
PHP中提供的imagecopyresized函数就可以用来生成真正的缩赂图片。
该函数的标推语法如下:语法:int imagecopyresized(int dst_im,int src_im,int dstX,int dstY,int srcX,int srcY,int dstW,int dstH,int srcW,int srcH);返回值:整数函数种类:图形处理内容说明:本函数可复制新图,并重新调整图片的大小尺寸。
参数都是目的在前,来源在后。
参数dst im及src_im为图片的handle。
参数dstX、dstY、srcX、srcY分别为目的及来源的坐标。
参数dstW、dstH、srcW、srcH分别为来源及目的的宽及高,欲调整的新图的尺寸就在这儿配置。
下面举个例子来说明这个函数的用法,对应的程序thumb.php如程序清单12—5所示。
程序清单12—5 thumb.php复制代码代码如下:<?// 本函数从源文件取出图像,设定成指定大小,并输出到目的文件// 源文件格式:gif,jpg,png// 目的文件格式:gif// $srcFile:源文件// $dstFile: 目标文件// $dstW:目标图片宽度// $dstH:目标文件高度function makethumb($srcFile,$dstFile,$dstW,$dstH){$data = GetImageSize($srcFile,&$info);switch ($data[2]){case 1:$imgsrc = @ImageCreateFromGIF($srcFile);break;case 2:$imgsrc = @ImageCreateFromJPEG($srcFile);break;case 3:$imgsrc = @ImageCreateFromPNG($srcFile);break;}$srcW = ImageSX($imgsrc);$srcH = ImageSY($imgsrc);$ni = ImageCreate($dstW,$dstH);ImageCopyResized($ni,$imgsrc,0,0,0,0,$dstW,$dstH,$srcW,$ srcH);Imagegif($ni,$dstFile);// 如果需要输出到浏览器,那么将上一句改为 ImageJpeg($ni);// 如果需要其他格式的图片,改动最后一句就可以了}>在这个例子中,首先通过getimagesize()函数获得源图片的`情况,再用 imagecreatefromgif()、imagecreatefromjpeg()或imagecreatefrompng()创建一个源位图$imgsrc,然后用imagecreate()函数创建一个目标位图,其长、宽各是源位图的一半。
ASP.NET画图全攻略

画图全攻略(上)教程,研发本文代码是基于beta2研发越来越多的web应用需要使用图表来进行数据显示和分析。
例如:投票结果显示,公司生产情况统计图显示分析等等。
利用图表来显示数据,具备直观,清楚等长处。
传统的asp技术是不支持画图表的,那么就不得不利用active x或java applets来实现这个功能。
新近出现的解决了这个问题,只要利用中关于图像显示的类,就能够画出丰富,动态的图表(如图1)。
本文将要讲述如何利用技术结合技术画条形图和饼图。
图1首先建立一个c#的类库。
打开,建立一个名为insight_cs.webcharts新的类库工程,将解决方案的名称改为insight,将class.cs文档名改为insight_cs.webcharts.cs,最后打开insight_cs.webcharts.cs文档。
其中代码如下: /*自定义类,通过输入不同的参数,这些类能够画不同的图像*/using system;using system.io;//用于文档存取using system.data;//用于数据访问using system.drawing;//提供画gdi+图像的基本功能using system.drawing.text;//提供画gdi+图像的高级功能using system.drawing.drawing2d;//提供画高级二维,矢量图像功能using system.drawing.imaging;//提供画gdi+图像的高级功能namespace insight_cs.webcharts{public class piechart{public piechart(){}public void render(string title, string subtitle, int width, int height, dataset chartdata, stream target) {const int side_length = 400;const int pie_diameter = 200;datatable dt = chartdata.tables[0];//通过输入参数,取得饼图中的总基数float sumdata = 0;foreach(datarow dr in dt.rows){sumdata += convert.tosingle(dr[1]);}//产生一个image对象,并由此产生一个graphics对象bitmap bm = new bitmap(width,height);graphics g = graphics.fromimage(bm);//配置对象g的属性g.scaletransform((convert.tosingle(width))/side_length,(convert.tosingle(height))/side_length);g.smoothingmode = smoothingmode.default;g.textrenderinghint = textrenderinghint.antialias;//画布和边的设定g.clear(color.white);g.drawrectangle(pens.black,0,0,side_length-1,side_length-1);//画饼图标题g.drawstring(title,new font("tahoma",24),brushes.black,new pointf(5,5));//画饼图的图例g.drawstring(subtitle,new font("tahoma",14),brushes.black,new pointf(7,35));//画饼图float curangle = 0;float totalangle = 0;for(int i=0;i<dt.rows.count;i++){curangle = convert.tosingle(dt.rows[i][1]) / sumdata * 360;g.fillpie(newsolidbrush(chartutil.getchartitemcolor(i)),100,65,pie_diameter,pie_diameter,totalangle,curangle);g.drawpie(pens.black,100,65,pie_diameter,pie_diameter,totalangle,curangle);totalangle += curangle;}//画图例框及其文字g.drawrectangle(pens.black,200,300,199,99);g.drawstring("legend",new font("tahoma",12,fontstyle.bold),brushes.black,new pointf(200,300));//画图例各项pointf boxorigin = new pointf(210,330);pointf textorigin = new pointf(235,326);float percent = 0;for(int i=0;i<dt.rows.count;i++){g.fillrectangle(new solidbrush(chartutil.getchartitemcolor(i)),boxorigin.x,boxorigin.y,20,10);g.drawrectangle(pens.black,boxorigin.x,boxorigin.y,20,10);percent = convert.tosingle(dt.rows[i][1]) / sumdata * 100;g.drawstring(dt.rows[i][0].tostring() + " - " + dt.rows[i][1].tostring() + " (" + percent.tostring("0") + "%)",new font("tahoma",10),brushes.black,textorigin);boxorigin.y += 15;textorigin.y += 15;}//通过response.outputstream,将图像的内容发送到浏览器bm.save(target, imageformat.gif);//回收资源bm.dispose();g.dispose();}}//画条形图public class barchart{public barchart(){}public void render(string title, string subtitle, int width, int height, dataset chartdata, stream target) {const int side_length = 400;const int chart_top = 75;const int chart_height = 200;const int chart_left = 50;const int chart_width = 300;datatable dt = chartdata.tables[0];//计算最高的点float highpoint = 0;foreach(datarow dr in dt.rows){if(highpoint<convert.tosingle(dr[1])){highpoint = convert.tosingle(dr[1]);}}//建立一个graphics对象实例bitmap bm = new bitmap(width,height);graphics g = graphics.fromimage(bm);//配置条图图像和文字属性g.scaletransform((convert.tosingle(width))/side_length,(convert.tosingle(height))/side_length); g.smoothingmode = smoothingmode.default;g.textrenderinghint = textrenderinghint.antialias;//设定画布和边g.clear(color.white);g.drawrectangle(pens.black,0,0,side_length-1,side_length-1);//画大标题g.drawstring(title,new font("tahoma",24),brushes.black,new pointf(5,5));//画小标题g.drawstring(subtitle,new font("tahoma",14),brushes.black,new pointf(7,35));//画条形图float barwidth = chart_width / (dt.rows.count * 2);pointf barorigin = new pointf(chart_left + (barwidth / 2),0);float barheight = dt.rows.count;for(int i=0;i<dt.rows.count;i++){barheight = convert.tosingle(dt.rows[i][1]) * 200 / highpoint;barorigin.y = chart_top + chart_height - barheight;g.fillrectangle(newsolidbrush(chartutil.getchartitemcolor(i)),barorigin.x,barorigin.y,barwidth,barheight);barorigin.x = barorigin.x + (barwidth * 2);}//配置边g.drawline(new pen(color.black,2),new point(chart_left,chart_top),new point(chart_left,chart_top + chart_height));g.drawline(new pen(color.black,2),new point(chart_left,chart_top + chart_height),new point(chart_left + chart_width,chart_top + chart_height));//画图例框和文字g.drawrectangle(new pen(color.black,1),200,300,199,99);g.drawstring("legend",new font("tahoma",12,fontstyle.bold),brushes.black,new pointf(200,300));//画图例pointf boxorigin = new pointf(210,330);pointf textorigin = new pointf(235,326);for(int i=0;i<dt.rows.count;i++){g.fillrectangle(new solidbrush(chartutil.getchartitemcolor(i)),boxorigin.x,boxorigin.y,20,10);g.drawrectangle(pens.black,boxorigin.x,boxorigin.y,20,10);g.drawstring(dt.rows[i][0].tostring() + " - " + dt.rows[i][1].tostring(),newfont("tahoma",10),brushes.black,textorigin);boxorigin.y += 15;textorigin.y += 15;}//输出图像bm.save(target, imageformat.gif);//资源回收bm.dispose();g.dispose();}}public class chartutil{public chartutil(){}public static color getchartitemcolor(int itemindex){color selectedcolor;switch(itemindex){case 0:selectedcolor = color.blue;break;case 1:selectedcolor = color.red;break;case 2:selectedcolor = color.yellow;break;case 3:selectedcolor = color.purple;break;default:selectedcolor = color.green;break;}return selectedcolor;}}}代码分析:1.引入一些namespaceusing system;using system.io;//用于文档存取using system.data;//用于数据访问using system.drawing;//提供画gdi+图像的基本功能using system.drawing.text;//提供画gdi+图像的高级功能using system.drawing.drawing2d;//提供画高级二维,矢量图像功能 using system.drawing.imaging;//提供画gdi+图像的高级功能这些namespace将在后面被应用。
c#生成图片缩略图的类(2种实现思路)

c#⽣成图⽚缩略图的类(2种实现思路)复制代码代码如下:/**//// <summary>/// ⽣成缩略图/// </summary>/// <param name="originalImagePath">源图路径(物理路径)</param>/// <param name="thumbnailPath">缩略图路径(物理路径)</param>/// <param name="width">缩略图宽度</param>/// <param name="height">缩略图⾼度</param>/// <param name="mode">⽣成缩略图的⽅式</param>public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) {Image originalImage = Image.FromFile(originalImagePath);int towidth = width;int toheight = height;int x = 0;int y = 0;int ow = originalImage.Width;int oh = originalImage.Height;switch (mode){case "HW"://指定⾼宽缩放(可能变形)break;case "W"://指定宽,⾼按⽐例toheight = originalImage.Height * width/originalImage.Width;break;case "H"://指定⾼,宽按⽐例towidth = originalImage.Width * height/originalImage.Height;break;case "Cut"://指定⾼宽裁减(不变形)if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight){oh = originalImage.Height;ow = originalImage.Height*towidth/toheight;y = 0;x = (originalImage.Width - ow)/2;}else{ow = originalImage.Width;oh = originalImage.Width*height/towidth;x = 0;y = (originalImage.Height - oh)/2;}break;default :break;}//新建⼀个bmp图⽚Image bitmap = new System.Drawing.Bitmap(towidth,toheight);//新建⼀个画板Graphics g = System.Drawing.Graphics.FromImage(bitmap);//设置⾼质量插值法g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置⾼质量,低速度呈现平滑程度g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//清空画布并以透明背景⾊填充g.Clear(Color.Transparent);//在指定位置并且按指定⼤⼩绘制原图⽚的指定部分g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),new Rectangle(x, y, ow,oh),GraphicsUnit.Pixel);try{//以jpg格式保存缩略图bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);}catch(System.Exception e){throw e;}finally{originalImage.Dispose();bitmap.Dispose();g.Dispose();}}关键⽅法Graphics.DrawImage见ms-help://FrameworkSDKv1.1.CHS/cpref/html/frlrfsystemdrawinggraphicsclassdrawimagetopic11.htm 4个重载⽅法,有直接返回Image对象的,有⽣成缩略图,并且保存到指定⽬录的!复制代码代码如下:using System.IO;using System.Drawing;using System.Drawing.Imaging;/// <summary>/// 图⽚处理类/// 1、⽣成缩略图⽚或按照⽐例改变图⽚的⼤⼩和画质/// 2、将⽣成的缩略图放到指定的⽬录下/// </summary>public class ImageClass{public Image ResourceImage;private int ImageWidth;private int ImageHeight;public string ErrMessage;/// <summary>/// 类的构造函数/// </summary>/// <param name="ImageFileName">图⽚⽂件的全路径名称</param>public ImageClass(string ImageFileName){ResourceImage=Image.FromFile(ImageFileName);ErrMessage="";}public bool ThumbnailCallback(){return false;}/// <summary>/// ⽣成缩略图重载⽅法1,返回缩略图的Image对象/// </summary>/// <param name="Width">缩略图的宽度</param>/// <param name="Height">缩略图的⾼度</param>/// <returns>缩略图的Image对象</returns>public Image GetReducedImage(int Width,int Height){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ReducedImage=ResourceImage.GetThumbnailImage(Width,Height,callb,IntPtr.Zero);return ReducedImage;}catch(Exception e){ErrMessage=e.Message;return null;}}/// <summary>/// ⽣成缩略图重载⽅法2,将缩略图⽂件保存到指定的路径/// </summary>/// <param name="Width">缩略图的宽度</param>/// <param name="Height">缩略图的⾼度</param>/// <param name="targetFilePath">缩略图保存的全⽂件名,(带路径),参数格式:D:Images ilename.jpg</param> /// <returns>成功返回true,否则返回false</returns>public bool GetReducedImage(int Width,int Height,string targetFilePath){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ReducedImage=ResourceImage.GetThumbnailImage(Width,Height,callb,IntPtr.Zero);ReducedImage.Save(@targetFilePath,ImageFormat.Jpeg);ReducedImage.Dispose();return true;}catch(Exception e){ErrMessage=e.Message;return false;}}/// <summary>/// ⽣成缩略图重载⽅法3,返回缩略图的Image对象/// </summary>/// <param name="Percent">缩略图的宽度百分⽐如:需要百分之80,就填0.8</param>/// <returns>缩略图的Image对象</returns>public Image GetReducedImage(double Percent){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ImageWidth=Convert.ToInt32(ResourceImage.Width*Percent);ImageHeight=Convert.ToInt32(ResourceImage.Width*Percent);ReducedImage=ResourceImage.GetThumbnailImage(ImageWidth,ImageHeight,callb,IntPtr.Zero);return ReducedImage;}catch(Exception e){ErrMessage=e.Message;return null;}}/// <summary>/// ⽣成缩略图重载⽅法4,返回缩略图的Image对象/// </summary>/// <param name="Percent">缩略图的宽度百分⽐如:需要百分之80,就填0.8</param>/// <param name="targetFilePath">缩略图保存的全⽂件名,(带路径),参数格式:D:Images ilename.jpg</param> /// <returns>成功返回true,否则返回false</returns>public bool GetReducedImage(double Percent,string targetFilePath){try{Image ReducedImage;Image.GetThumbnailImageAbort callb=new Image.GetThumbnailImageAbort(ThumbnailCallback); ImageWidth=Convert.ToInt32(ResourceImage.Width*Percent);ImageHeight=Convert.ToInt32(ResourceImage.Width*Percent);ReducedImage=ResourceImage.GetThumbnailImage(ImageWidth,ImageHeight,callb,IntPtr.Zero); ReducedImage.Save(@targetFilePath,ImageFormat.Jpeg);ReducedImage.Dispose();return true;}catch(Exception e){ErrMessage=e.Message;return false;}}}。
如何实现asp无组件生成缩略图_

如何实现asp无组件生成缩略图_网上有不少生成缩略图的ASP组件。
若你的虚拟空间不支持注册新组件,可能会感觉自己的网站失色不少。
心晴不才,结合网上资源写了个无组件生成缩略图程序,仅供参考。
还是先看看基础部分吧。
首先,我们知道在页面中显示图片是如下代码:img src="pic.gif" border="0" width="300" height="260"src是图片路径,border掌握图片边缘宽度,width是图片的长度,height是图片的高度。
缩略图的生成其实就是在原始尺寸上缩放。
但一般为了尽量少失真,我们都会按比例缩放。
于是,猎取图片的长宽尺寸也就成了生成缩略图的重点。
下面便是编写无组件生成缩略图的步骤:1.无组件猎取图片大小以前刚学ASP不久时看到过一篇利用ASCII码实现无组件猎取图片尺寸的文章。
后来试了试,发觉在猎取jpg类图片尺寸时总是不能正确显示,在网上查了查,居然有不少网站转载这个程序,但没有一家指出此程序的缺陷,也就更谈不上解决缺陷的方法了。
后来又google了一下,最终找到了一篇介绍利用ADODB.stream猎取图片尺寸的文章,按其介绍的方法,修改里面的代码试了试,效果真的还不错,现在将其拿出来与大家分享:利用ADODB.stream猎取图片尺寸的通用类%'//////////// GPS:Get Picture Size ////////////// '//////////////利用ADODB.stream猎取图片尺寸//////////////'/////////Cited By Leon(心晴) 2021年8月11日//////////Class GPSDim asoPrivate Sub Class_InitializeSet aso=CreateObject("Adodb.Stream")aso.Mode=3aso.Type=1aso.OpenEnd SubPrivate Sub Class_Terminateset aso=nothingEnd SubPrivate Function Bin2Str(Bin)Dim I, StrFor I=1 to LenB(Bin)clow=MidB(Bin,I,1)if AscB(clow)128 thenStr = Str Chr(ASCB(clow))ElseI=I+1if I = LenB(Bin) then Str = Str Chr(ASCW(MidB(Bin,I,1)clow))end IfNextBin2Str = StrEnd FunctionPrivate Function Num2Str(num,base,lens)'GPS (2021-8-11)dim retret = ""while(num=base)ret = (num mod base) retnum = (num - num mod base)/basewendNum2Str = right(string(lens,"0") num ret,lens) End FunctionPrivate Function Str2Num(str,base) 'GPS (2021-8-11)dim retret = 0for i=1 to len(str)ret = ret *base + cint(mid(str,i,1)) nextStr2Num=retEnd FunctionPrivate Function BinVal(bin)'GPS (2021-8-11)dim retret = 0for i = lenb(bin) to 1 step -1ret = ret *256 + ascb(midb(bin,i,1)) nextBinVal=retEnd FunctionPrivate Function BinVal2(bin)'GPS (2021-8-11)dim retret = 0for i = 1 to lenb(bin)ret = ret *256 + ascb(midb(bin,i,1)) nextBinVal2=retEnd Function'///以下是调用代码///Function getImageSize(filespec)'GPS (2021-8-11)dim ret(3)aso.LoadFromFile(filespec)bFlag=aso.read(3)select case hex(binVal(bFlag))case "4E5089":aso.read(15)ret(0)="PNG"ret(1)=BinVal2(aso.read(2))aso.read(2)ret(2)=BinVal2(aso.read(2))case "464947":aso.read(3)ret(0)="GIF"ret(1)=BinVal(aso.read(2))ret(2)=BinVal(aso.read(2))case "535746":aso.read(5)binData=aso.Read(1)sConv=Num2Str(ascb(binData),2 ,8)nBits=Str2Num(left(sConv,5),2)sConv=mid(sConv,6)while(len(sConv)nBits*4)binData=aso.Read(1)sConv=sConvNum2Str(ascb(binData),2 ,8)wendret(0)="SWF"ret(1)=int(abs(Str2Num(mid(sConv,1*nBits+1,nBits),2 )-Str2Num(mid(sConv,0*nBits+1,nBits),2))/20)ret(2)=int(abs(Str2Num(mid(sConv,3*nBits+1,nBits),2 )-Str2Num(mid(sConv,2*nBits+1,nBits),2))/20)case "FFD8FF":dodo: p1=binVal(aso.Read(1)): loop while p1=255 and not aso.EOSif p1191 and p1196 then exit do else aso.read(binval2(aso.Read(2))-2)do:p1=binVal(aso.Read(1)):loop while p1255 and not aso.EOSloop while trueaso.Read(3)ret(0)="JPG"ret(2)=binval2(aso.Read(2))ret(1)=binval2(aso.Read(2))case else:if left(Bin2Str(bFlag),2)="BM" thenaso.Read(15)ret(0)="BMP"ret(1)=binval(aso.Read(4))ret(2)=binval(aso.Read(4))elseret(0)=""end ifend selectret(3)="width=""" ret(1) """ height="""ret(2) """"getimagesize=retEnd FunctionEnd Class%将以上代码复制生成GPS.asp文件,这样无组件猎取图片尺寸的通用类就OK了。
php生成缩略图的两种方法

php生成缩略图的两种方法php生成缩略图的两种方法在php中如果要生成缩略图有什么办法呢?以下是店铺整理的两种方法,希望对大家有用,更多消息请关注应届毕业生网。
核心代码如下public function getImage(){// create instance$basePath = base_path('public/');$md5 = 'b8c3bf0b10a81c5b6a98c527868a0000';$sub1 = substr($md5, 0, 1);$sub2 = substr($md5, 1, 2);$subPath = sprintf("image/%s/%s/%s%s.jpg", $sub1, $sub2, $md5, '300x300');$sourcePath = sprintf("image/%s/%s/%s.jpg", $sub1, $sub2, $md5);//截成100x80的缩略图//$image = $this->getCropper($basePath.$sourcePath,$basePath.$subPath, 300, 300);$image = $this->getCrops($basePath.$sourcePath,$basePath.$subPath, 300, 300);}//生成缩略图function getCropper($source_path,$NewImagePath, $target_width, $target_height){$source_info = getimagesize($source_path);$source_width = $source_info[0];$source_height = $source_info[1];$source_mime = $source_info['mime'];$source_ratio = $source_height / $source_width; $target_ratio = $target_height / $target_width;// 源图过高if ($source_ratio > $target_ratio){$cropped_width = $source_width;$cropped_height = $source_width * $target_ratio; $source_x = 0;$source_y = ($source_height - $cropped_height) / 2; }// 源图过宽elseif ($source_ratio < $target_ratio){$cropped_width = $source_height / $target_ratio; $cropped_height = $source_height;$source_x = ($source_width - $cropped_width) / 2; $source_y = 0;}// 源图适中else{$cropped_width = $source_width;$cropped_height = $source_height;$source_x = 0;$source_y = 0;}switch ($source_mime){case 'image/gif':$source_image = imagecreatefromgif($source_path);break;case 'image/jpeg':$source_image = imagecreatefromjpeg($source_path);break;case 'image/png':$source_image = imagecreatefrompng($source_path);break;default:return false;break;}$target_image = imagecreatetruecolor($target_width, $target_height);$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);// 图片裁剪imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);// 图片缩放imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);header('Content-Type: image/jpeg');imagejpeg($target_image,$NewImagePath,100);imagedestroy($source_image);imagedestroy($target_image);imagedestroy($cropped_image);}//生成缩略图,填充白边functiongetCrops($src_path,$NewImagePath,$width,$height){ //源图对象$src_image = imagecreatefromstring(file_get_contents($src_path));$source_info = getimagesize($src_path);$source_mime = $source_info['mime'];$src_width = imagesx($src_image);$src_height = imagesy($src_image);switch ($source_mime){case 'image/gif':$src_image = imagecreatefromgif($src_path);break;case 'image/jpeg':$src_image = imagecreatefromjpeg($src_path);break;case 'image/png':$src_image = imagecreatefrompng($src_path);break;default:return false;break;}//生成等比例的缩略图//$tmp_image_width = 0;//$tmp_image_height = 0;if ($src_width / $src_height >= $width / $height) {$tmp_image_width = $width;$tmp_image_height = round($tmp_image_width * $src_height / $src_width);} else {$tmp_image_height = $height;$tmp_image_width = round($tmp_image_height * $src_width / $src_height);}$tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);imagecopyresampled($tmpImage, $src_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);//添加白边$final_image = imagecreatetruecolor($width, $height);$color = imagecolorallocate($final_image, 255, 255, 255);imagefill($final_image, 0, 0, $color);$x = round(($width - $tmp_image_width) / 2);$y = round(($height - $tmp_image_height) / 2);imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);//输出图片header('Content-Type: image/jpeg');imagejpeg($final_image,$NewImagePath,100);imagedestroy($src_image);imagedestroy($final_image);}。
php实现依据url自动生成缩略图的方法__2

php实现依据url自动生成缩略图的方法_ 本文实例讲解并描述了php实现依据url自动生成缩略图的方法,是特别有用的功能。
分享给大家供大家参考。
具体方法如下:原理:设置apache rewrite ,当图片不存在时,调用php创建图片。
例如:原图路径为:http://localhost/upload/news/2021/07/21/1.jpg 缩略图路径为:http://localhost/supload/news/2021/07/21/1.jpg当访问http://localhost/supload/news/2021/07/21/1.jpg 时,如图片存在,则显示图片。
否则,调用createthumb.php生成图片。
名目结构如下:/PicThumb.class.php/ThumbConfig.php/upload/news/2021/07/21/1.jpg/upload/article/2021/07/21/2.jpg/supload/.htaccess/supload/watermark.png/supload/createthumb.phphttp://localhost/ 指向名目需要开启apache rewrite:sudo a2enmod rewrite.htaccess文件如下:IfModule mod_rewrite.cRewriteEngine On# '-s' (is regular file, with size)# '-l' (is symbolic link)# '-d' (is directory)# 'ornext|OR' (or next condition)# 'nocase|NC' (no case)# 'last|L' (last rule)RewriteCond %{REQUEST_FILENAME} -s [OR]RewriteCond %{REQUEST_FILENAME} -l [OR]RewriteCond %{REQUEST_FILENAME} -dRewriteRule ^.*$ - [NC,L]RewriteRule^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L] /IfModulecreatethumb.php文件如下:?phpdefine('_PATH', dirname(dirname(__FILE__))); // 站点名目require(_PATH.'/PicThumb.class.php'); // include PicThumb.class.phprequire(_PATH.'/ThumbConfig.php'); // include ThumbConfig.php$logfile = _PATH.'/createthumb.log'; // 日志文件$source_path = _PATH.'/upload/'; // 原路径$dest_path = _PATH.'/supload/'; // 目标路径$path = isset($_GET['path'])? $_GET['path'] : ''; // 访问的图片URL// 检查pathif(!$path){exit();}// 猎取图片URI$relative_url = str_replace($dest_path, '', _PATH.$path);// 猎取type$type = substr($relative_url, 0, strpos($relative_url, '/'));// 猎取config$config = isset($thumb_config[$type])? $thumb_config[$type] : '';// 检查configif(!$config || !isset($config['fromdir'])){exit();}// 原图文件$source = str_replace('/'.$type.'/', '/'.$config['fromdir'].'/',$source_path.$relative_url);// 目标文件$dest = $dest_path.$relative_url;// 创建缩略图$obj = new PicThumb($logfile);$obj-set_config($config);if($obj-create_thumb($source, $dest)){ob_clean();header('content-type:'.mime_content_type($dest)); exit(file_get_contents($dest));}?ThumbConfig.php文件如下:?php$thumb_config = array('news' = array('fromdir' = 'news', // 来源名目'type' = 'fit','width' = 100,'height' = 100,'bgcolor' = '#FF0000'),'news_1' = array('fromdir' = 'news','type' = 'fit','width' = 200,'height' = 200,'bgcolor' = '#FFFF00'),'article' = array('fromdir' = 'article','type' = 'crop','width' = 250,'height' = 250,'watermark' = _PATH.'/supload/watermark.png'));?访问这三个路径后会按config自动生成缩略图http://localhost/supload/news/2021/07/21/1.jpghttp://localhost/supload/news_1/2021/07/21/1.jpg http://localhost/supload/article/2021/07/21/2.jpg 盼望本文所述对大家的php程序设计有所关心。
无组件上传图片源代码

end if
if file.filesize>1024000 then
response.write "<span style=""font-family: 宋体; font-size: 9pt"">图片大小超过了限制 [ <a href=# onclick=history.go(-1)>重新上传</a> ]</span>"
response.end
end if
randomize
rannum=int(90000*rnd)+10000
filename=formPath&year(now)&month(now)&day(now)&hour(now)&minute(now)&second(now)&rannum&"."&fileExt
set file=upload.file(formName) ''生成一个文件对象
if file.filesize<100 then
response.write "<span style=""font-family: 宋体; font-size: 9pt"">请先选择你要上传的图片 [ <a href=# onclick=history.go(-1)>重新上传</a> ]</span>"
''在目录后加(/)
if right(formPath,1)<>"/" then formPath=formPath&"/"
struts2 或 spring mvc上传图片生成高清缩略图,亲测可以用哦

struts2 或spring mvc上传图片生成高清缩略图,亲测可以用哦版权声明:本文为博主原创文章,未经博主允许不得转载。
教你在struts2上传图片生成高清缩略图的功能运用在spring MVC上,各们亲!教你举一反三:近段时间在运用了spring mvc+spring3.x+mybatis3.x框架开发项目,碰到一个问题,上传图片并生成缩略图。
在网上找了很多资料都没有看到我想要的功能,要不就单纯上传图片,而且代码简单没什么实用处。
要不就是上传文件,不是我想找的。
记得之前struts2也有上传图片生成高清缩略图的功能,于是看了看,有两种方法,不过大同小异。
代码如下以下是struts2也有上传图片哦。
如果要看spring mvc上传图片请直接拉下下第一种:清晰度不高;UploadAction [java] view plaincopypackage nyuan.upload; import java.io.File; importcom.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport { private static final long serialVersionUID = -8204063374280945416L; private File upload;// 路径private String uploadFileName;// 原文件名private String uploadContentType;// 文件类型public String upload() throws Exception { UploadUtil uploadutil = newUploadUtil(); uploadutil.uploadImage1(getUpload(), getUploadContentType(), getUploadFileName());return "success"; } public File getUpload(){ return upload; } public void setUpload(File upload) { this.upload =upload; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName){ this.uploadFileName = uploadFileName; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType){ this.uploadContentType = uploadContentType; } } /**** 上传图片工具类* 大图片路径,生成小图片路径,* 大图片文件名,生成小图片文名,* 生成小图片宽度,生成小图片高度,* 是否等比缩放(默认为true))** @author Administrator**/UploadUtil[java] view plaincopypackage nyuan.upload; import java.io.File; import java.io.FileInputStream; importjava.io.FileOutputStream; import java.io.IOException;import java.text.DateFormat; importjava.text.SimpleDateFormat; import java.util.Date; import java.util.Random; importorg.apache.struts2.ServletActionContext; /** * * 上传图片工具类* 大图片路径,生成小图片路径, * 大图片文件名,生成小图片文名, * 生成小图片宽度,生成小图片高度, * 是否等比缩放(默认为true)) * * @author Administrator * */ public class UploadUtil { private String imagePath = "/image/"+newSimpleDateFormat("yyyyMMddHH").format(new Date())+"";// 配置图片路径private String image_smallPath ="/image_small/"+newSimpleDateFormat("yyyyMMddHH").format(new Date())+"";// 配置小图片路径/** * * @param request / * @param getUpload 路径* @param getUploadContentType 文件类型* @param getUploadFileName 原文件名* @return *@throws IOException */ public void uploadImage1(File getUpload, String getUploadContentType, String getUploadFileName) throws IOException{ String getImagePath = ServletActionContext.getServletContext().getRealPath(imagePa th); String getImage_smallPath = ServletActionContext.getServletContext().getRealPath(image_s mallPath); File image = new File(getImagePath);if (!image.exists()){ image.mkdir(); } File image_small = new File(getImage_smallPath); if (!image_small.exists()){ image_small.mkdir(); }// 得到上传文件的后缀名String uploadName = getUploadContentType; System.out.println("图片类型------------"+uploadName); String lastuploadName =uploadName.substring( uploadName.index Of("/") + 1, uploadName.length());System.out.println("得到上传文件的后缀名------------"+lastuploadName); // 得到文件的新名字String fileNewName =generateFileName(getUploadFileName);System.out.println("// 得到文件的新名字------------"+fileNewName);FileOutputStream fos = new FileOutputStream(getImagePath + "/" + fileNewName); FileInputStream fis = new FileInputStream(getUpload); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0){ fos.write(buffer, 0, len); } DwindlePic mypic = new DwindlePic();mypic.s_pic(getImagePath + "/", getImage_smallPath + "/", fileNewName, fileNewName, 110, 110, false);//最后返回图片路径imagePath =imagePath+"/"+fileNewName; image_smallPath = image_smallPath+"/"+fileNewName; }/** * 传入原图名称,,获得一个以时间格式的新名称* @param fileName原图名称* @return */ private String generateFileName(String fileName){ DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String formatDate = format.format(new Date()); int random = new Random().nextInt(10000); intposition = stIndexOf("."); String extension = fileName.substring(position); return formatDate + random + extension; } public String getImagepath() { return imagePath; } public String getImageSmallpath() { returnimage_smallPath; } }大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))DwindlePic [java] view plaincopypackagenyuan.upload; import java.io.*; importcom.sun.image.codec.jpeg.*; import java.awt.image.*;import java.awt.*; import java.applet.*; /** * s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true)) * * @author Administrator * */ public class DwindlePic { String InputDir; // 输入图路径String OutputDir; // 输出图路径String InputFileName; // 输入图文件名String OutputFileName; // 输出图文件名int OutputWidth = 110; // 默认输出图片宽int OutputHeight = 110; // 默认输出图片高int rate = 0; boolean proportion = true; // 是否等比缩放标记(默认为等比缩放) public DwindlePic() { // 初始化变量InputDir = ""; OutputDir = ""; InputFileName = ""; OutputFileName = ""; OutputWidth = 110; OutputHeight = 110;rate = 0; } public boolean s_pic(){ // BufferedImage image; // String NewFileName; // 建立输出文件对象File file = new File(OutputDir + OutputFileName); FileOutputStream tempout = null; try{ tempout = newFileOutputStream(file); } catch (Exception ex){ System.out.println(ex.toString()); } Image img = null; Toolkit tk =Toolkit.getDefaultToolkit(); Applet app = new Applet(); MediaTracker mt = newMediaTracker(app); try { img =tk.getImage(InputDir + InputFileName);mt.addImage(img, 0);mt.waitForID(0); } catch (Exception e){ e.printStackTrace(); }if (img.getWidth(null) == -1){ System.out.println(" can't read,retry!" +"<BR>"); return false; } else{ int new_w; int new_h;if (this.proportion == true) { // 判断是否是等比缩放.// 为等比缩放计算输出的图片宽度及高度double rate1 = ((double) img.getWidth(null))/ (double) OutputWidth + 0.1; doublerate2 = ((double) img.getHeight(null))/ (double) OutputHeight + 0.1; double rate = rate1 > rate2 ? rate1 : rate2; new_w = (int) (((double) img.getWidth(null)) / rate);new_h = (int) (((double) img.getHeight(null)) /rate); } else { new_w = OutputWidth; // 输出的图片宽度new_h = OutputHeight; // 输出的图片高度} BufferedImage buffImg = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.createGraphics();g.setColor(Color.white); g.fillRect(0, 0, new_w, new_h); g.drawImage(img, 0, 0, new_w, new_h, null); g.dispose();JPEGImageEncoder encoder =JPEGCodec.createJPEGEncoder(tempout); try { encoder.encode(buffImg);tempout.close(); } catch (IOException ex) { System.out.println(ex.toString());} } return true; } public boolean s_pic(String InputDir, String OutputDir,String InputFileName, String OutputFileName) { // 输入图路径this.InputDir = InputDir; // 输出图路径this.OutputDir = OutputDir;// 输入图文件名this.InputFileName = InputFileName; // 输出图文件名this.OutputFileName = OutputFileName; returns_pic(); } /** *s_pic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true)) * @param InputDir * @param OutputDir * @param InputFileName *@param OutputFileName * @param width * @param height * @param gp * @return*/ public boolean s_pic(String InputDir, String OutputDir, String InputFileName, String OutputFileName, int width, int height, boolean gp) { // 输入图路径this.InputDir = InputDir; // 输出图路径this.OutputDir= OutputDir; // 输入图文件名this.InputFileName = InputFileName; // 输出图文件名this.OutputFileName = OutputFileName;// 设置图片长宽setW_H(width, height);// 是否是等比缩放标记this.proportion = gp; return s_pic(); } public void setInputDir(String InputDir) { this.InputDir = InputDir; } public void setOutputDir(String OutputDir){ this.OutputDir = OutputDir; }public void setInputFileName(String InputFileName){ this.InputFileName = InputFileName; } public void setOutputFileName(String OutputFileName){ this.OutputFileName = OutputFileName; } public void setOutputWidth(int OutputWidth){ this.OutputWidth = OutputWidth; } public void setOutputHeight(int OutputHeight){ this.OutputHeight = OutputHeight; } public void setW_H(int width, int height){ this.OutputWidth = width;this.OutputHeight = height; } }看看效果吧!第二种,清晰度还可以接受[java] view plaincopypackage com.xiyuan.upload; importjava.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.imageio.ImageIO; import org.apache.struts2.ServletActionContext; /** * * 上传图片工具类大图片路径,生成小图片路径, 大图片文件名,生成小图片文名, 生成小图片宽度,生成小图片高度, 是否等比缩放(默认为true)) * * @author Administrator * */ public class UploadUtil { private String imagePath = "/imageFile/" + newSimpleDateFormat("yyyyMMddHH").format(new Date()) + "";// 配置图片路径/** * * @param getUpload * 路径* @param getUploadContentType * 文件类型* @param getUploadFileName * 原文件名* @return * @throws IOException */ public void uploadImage1(File getUpload, String getUploadContentType, String getUploadFileName) throws IOException { String getImagePath = ServletActionContext.getServletContext().getRealPath(imagePa th); File image = new File(getImagePath);if (!image.exists()){ image.mkdir(); } // 得到上传文件的后缀名String uploadName = getUploadContentType; System.out.println("图片类型------------" + uploadName); String lastuploadName =uploadName.substring(uploadName.indexOf("/") + 1, uploadName.length()); System.out.println("得到上传文件的后缀名------------" + lastuploadName);// 得到文件的新名字String fileNewName = generateFileName(getUploadFileName);System.out.println("// 得到文件的新名字------------" + fileNewName); // FileOutputStream fos = new FileOutputStream(getImagePath + "/" + // fileNewName); // // FileInputStream fis = new FileInputStream(getUpload);// byte[] buffer = new byte[1024]; // int len = 0;// while ((len = fis.read(buffer)) > 0) { //fos.write(buffer, 0, len); // } // 最后返回图片路径imagePath = imagePath + "/" + fileNewName; System.out.println(" 回图片路径" + getUpload); System.out.println(" //最后返回图片路径" + imagePath); BufferedImage srcBufferImage = ImageIO.read(getUpload);System.out.println(" w " + srcBufferImage.getWidth() + " w " + srcBufferImage.getHeight()); BufferedImage scaledImage; ScaleImage scaleImage = ScaleImage.getInstance(); int yw = srcBufferImage.getWidth(); int yh = srcBufferImage.getHeight(); int w = 110, h = 110; // 如果上传图片宽高比压缩的要小则不压缩if (w > yw && h > yh){ FileOutputStream fos = new FileOutputStream(getImagePath + "/" + fileNewName); FileInputStream fis = new FileInputStream(getUpload);byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0){ fos.write(buffer, 0,len); } } else{ scaledImage =scaleImage.imageZoomOut(srcBufferImage, w, h); FileOutputStream out = new FileOutputStream(getImagePath + "/" + fileNewName);ImageIO.write(scaledImage, "jpeg",out); } } /** * 传入原图名称,,获得一个以时间格式的新名称* *@param fileName * 原图名称* @return */ private String generateFileName(String fileName) { DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String formatDate = format.format(new Date()); int random = new Random().nextInt(10000); int position = stIndexOf("."); String extension = fileName.substring(position); return formatDate + random + extension; } public String getImagepath() { return imagePath; } }ScaleImage [java] view plaincopypackage com.xiyuan.upload; import java.awt.image.BufferedImage; public class ScaleImage { private int width; private int height; private int scaleWidth; private double support = (double) 3.0; private double PI = (double) 3.14159265358978; private double[] contrib;private double[] normContrib; private double[] tmpContrib; private int nDots; private int nHalfDots; /** * Start: Use Lanczos filter toreplace the original algorithm for image * scaling. Lanczos improves quality of the scaled image modify by :blade */ private static ScaleImage instance = new ScaleImage(); private ScaleImage(){}; public static ScaleImage getInstance(){ return instance; } public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) { width = srcBufferImage.getWidth(); height = srcBufferImage.getHeight(); scaleWidth = w; if (DetermineResultSize(w, h) == 1){ return srcBufferImage; } CalContrib(); BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);BufferedImage pbFinalOut = VerticalFiltering(pbOut, h); return pbFinalOut; } /** * 决定图像尺寸*/ private int DetermineResultSize(int w, int h) { double scaleH, scaleV; scaleH = (double) w / (double) width; scaleV = (double) h / (double) height; // ????判断????scaleH,scaleV,不做放大操?? if (scaleH >= 1.0 && scaleV >= 1.0) { return 1; } return 0; } // end of DetermineResultSize()private double Lanczos(int i, int inWidth, int outWidth, doubleSupport) { double x; x = (double) i * (double) outWidth / (double) inWidth; return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)/ (x * PI / Support); } // end of Lanczos() //// Assumption: same horizontal and vertical scaling factor// private void CalContrib() { nHalfDots = (int) ((double) width * support / (double) scaleWidth);nDots = nHalfDots * 2 + 1; try{ contrib = new double[nDots]; normContrib = new double[nDots]; tmpContrib = new double[nDots]; } catch (Exception e){ System.out.println("initcontrib,normContrib,tmpContrib" + e); }int center = nHalfDots; contrib[center] = 1.0; double weight = 0.0; int i = 0; for (i = 1;i <= center; i++) { contrib[center + i] = Lanczos(i, width, scaleWidth, support); weight += contrib[center + i]; } for (i = center - 1; i >= 0; i--) { contrib[i] = contrib[center * 2 - i]; } weight = weight * 2 + 1.0; for (i = 0; i <= center; i++) { normContrib[i] = contrib[i] / weight; } for (i = center+ 1; i < nDots; i++) { normContrib[i] = normContrib[center * 2 - i]; } } // end of CalContrib() // 处理边缘private void CalTempContrib(int start, int stop) { double weight = 0; int i = 0; for (i = start; i <= stop; i++) { weight += contrib[i]; } for (i = start; i <= stop; i++) { tmpContrib[i] = contrib[i] / weight; } } // end of CalTempContrib() private int GetRedValue(int rgbValue) { int temp = rgbValue & 0x00ff0000; return temp >> 16; } private int GetGreenValue(int rgbValue) { int temp = rgbValue & 0x0000ff00; return temp >> 8; } private int GetBlueValue(int rgbValue) { return rgbValue & 0x000000ff; } private int ComRGB(int redValue, int greenValue, int blueValue){ return (redValue << 16) + (greenValue<< 8) + blueValue; } // 行水平滤?? private int HorizontalFilter(BufferedImage bufImg, int startX,int stopX, int start, int stop, int y, double[] pContrib) { double valueRed = 0.0;double valueGreen = 0.0; double valueBlue = 0.0;int valueRGB = 0; int i, j; for (i = startX, j = start; i <= stopX; i++, j++){ valueRGB = bufImg.getRGB(i, y); valueRed += GetRedValue(valueRGB) * pContrib[j]; valueGreen += GetGreenValue(valueRGB) * pContrib[j]; valueBlue += GetBlueValue(valueRGB) *pContrib[j]; } valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),Clip((int) valueBlue)); return valueRGB; } // end of HorizontalFilter() // 图片水平滤波private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) { int dwInW = bufImage.getWidth(); int dwInH =bufImage.getHeight(); int value = 0; BufferedImage pbOut = new BufferedImage(iOutW, dwInH, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < iOutW; x++) { int startX;int start; int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5); int y = 0; startX = X - nHalfDots; if (startX < 0){ startX = 0; start = nHalfDots - X; } else{ start = 0; }int stop; int stopX = X + nHalfDots;if (stopX > (dwInW - 1)) { stopX = dwInW - 1; stop = nHalfDots + (dwInW - 1 - X); } else { stop = nHalfDots * 2; } if (start> 0 || stop < nDots - 1){ CalTempContrib(start, stop);for (y = 0; y < dwInH; y++){ value = HorizontalFilter(bufImage, startX, stopX, start, stop, y, tmpContrib); pbOut.setRGB(x, y, value); } } else{ for (y = 0; y < dwInH; y++){ value = HorizontalFilter(bufImage, startX, stopX, start, stop, y, normContrib); pbOut.setRGB(x, y, value); } } } return pbOut; } // end of HorizontalFiltering() private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY, int start, int stop, int x, double[] pContrib) { double valueRed = 0.0;double valueGreen = 0.0; double valueBlue = 0.0; int valueRGB = 0; int i, j; for (i = startY, j = start; i <= stopY; i++, j++){ valueRGB = pbInImage.getRGB(x, i); valueRed += GetRedValue(valueRGB) * pContrib[j]; valueGreen += GetGreenValue(valueRGB) * pContrib[j]; valueBlue += GetBlueValue(valueRGB) * pContrib[j];//System.out.println(valueRed+"->"+Clip((int)valueRed)+"< ;-"); // //System.out.println(valueGreen+"->"+Clip((int)valueGreen)+ "<-"); //System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"& lt;-"+"-->"); } valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),Clip((int) valueBlue)); //System.out.println(valueRGB); return valueRGB; } // end of VerticalFilter() private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) { int iW = pbImage.getWidth();int iH = pbImage.getHeight(); int value = 0; BufferedImage pbOut = new BufferedImage(iW, iOutH,BufferedImage.TYPE_INT_RGB); for (int y = 0; y < iOutH; y++) { int startY;int start; int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5); startY = Y - nHalfDots; if (startY < 0){ startY = 0; start = nHalfDots - Y; } else{ start = 0; }int stop; int stopY = Y + nHalfDots;if (stopY > (int) (iH - 1)) { stopY = iH - 1; stop = nHalfDots + (iH - 1 -Y); } else { stop = nHalfDots * 2; } if (start> 0 || stop < nDots - 1){ CalTempContrib(start, stop);for (int x = 0; x < iW; x++) { value = VerticalFilter(pbImage, startY, stopY, start, stop,x, tmpContrib); pbOut.setRGB(x, y, value); } } else{ for (int x = 0; x < iW; x++){ value = VerticalFilter(pbImage, startY, stopY, start, stop, x,normContrib); pbOut.setRGB(x, y, value); } } } return pbOut; } // end of VerticalFiltering()private int Clip(int x) { if (x < 0)return 0; if (x > 255) return 255; return x; } /** * End: Use Lanczos filter to replace the original algorithm for image * scaling. Lanczos improves quality of the scaled image modify by :blade */ } 看看第二种效果怎样。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
网上有不少生成缩略图的ASP组件。
若你的虚拟空间不支持注册新组件,可能会感觉自己的网站失色不少。
心晴不才,结合网上资源写了个无组件生成缩略图程序,仅供参考。
还是先看看基础部分吧。
首先,我们知道在页面中显示图片是如下代码:<img src="pic.gif" border="0" width="300" height="260">src是图片路径,border控制图片边缘宽度,width是图片的长度,height是图片的高度。
缩略图的生成其实就是在原始尺寸上缩放。
但一般为了尽量少失真,我们都会按比例缩放。
于是,获取图片的长宽尺寸也就成了生成缩略图的重点。
下面便是编写无组件生成缩略图的步骤:1.无组件获取图片大小以前刚学ASP不久时看到过一篇利用ASCII码实现无组件获取图片尺寸的文章。
后来试了试,发现在获取jpg类图片尺寸时总是不能正确显示,在网上查了查,居然有不少网站转载这个程序,但没有一家指出此程序的缺陷,也就更谈不上解决缺陷的办法了。
后来又google了一下,终于找到了一篇介绍利用ADODB.stream获取图片尺寸的文章,按其介绍的方法,修改里面的代码试了试,效果真的还不错,现在将其拿出来与大家分享:利用ADODB.stream获取图片尺寸的通用类<%'//////////// GPS:Get Picture Size //////////////'//////////////利用ADODB.stream获取图片尺寸//////////////'/////////Cited By Leon(心晴)2005年8月11日//////////Class GPSDim asoPrivate Sub Class_InitializeSet aso=CreateObject("Adodb.Stream")aso.Mode=3aso.Type=1aso.OpenEnd SubPrivate Sub Class_Terminateset aso=nothingEnd SubPrivate Function Bin2Str(Bin)Dim I, StrFor I=1 to LenB(Bin)clow=MidB(Bin,I,1)if AscB(clow)<128 thenStr = Str & Chr(ASCB(clow))ElseI=I+1if I <= LenB(Bin) then Str = Str & Chr(ASCW(MidB(Bin,I,1)&clow))end IfNextBin2Str = StrEnd FunctionPrivate Function Num2Str(num,base,lens)'GPS (2005-8-11)dim retret = ""while(num>=base)ret = (num mod base) & retnum = (num - num mod base)/basewendNum2Str = right(string(lens,"0") & num & ret,lens) End FunctionPrivate Function Str2Num(str,base)'GPS (2005-8-11)dim retret = 0for i=1 to len(str)ret = ret *base + cint(mid(str,i,1))nextStr2Num=retEnd FunctionPrivate Function BinVal(bin)'GPS (2002-8-11)dim retret = 0for i = lenb(bin) to 1 step -1ret = ret *256 + ascb(midb(bin,i,1))nextBinVal=retEnd FunctionPrivate Function BinVal2(bin)'GPS (2002-8-11)dim retret = 0for i = 1 to lenb(bin)ret = ret *256 + ascb(midb(bin,i,1))nextBinVal2=retEnd Function'///以下是调用代码///Function getImageSize(filespec)'GPS (2002-8-11)dim ret(3)aso.LoadFromFile(filespec)bFlag=aso.read(3)select case hex(binVal(bFlag))case "4E5089":aso.read(15)ret(0)="PNG"ret(1)=BinVal2(aso.read(2))aso.read(2)ret(2)=BinVal2(aso.read(2))case "464947":aso.read(3)ret(0)="GIF"ret(1)=BinVal(aso.read(2))ret(2)=BinVal(aso.read(2))case "535746":aso.read(5)binData=aso.Read(1)sConv=Num2Str(ascb(binData),2 ,8)nBits=Str2Num(left(sConv,5),2)sConv=mid(sConv,6)while(len(sConv)<nBits*4)binData=aso.Read(1)sConv=sConv&Num2Str(ascb(binData),2 ,8)wendret(0)="SWF"ret(1)=int(abs(Str2Num(mid(sConv,1*nBits+1,nBits),2)-Str2Num(mid(sConv,0*nBits+1,nBits),2) )/20)ret(2)=int(abs(Str2Num(mid(sConv,3*nBits+1,nBits),2)-Str2Num(mid(sConv,2*nBits+1,nBits),2) )/20)case "FFD8FF":dodo: p1=binVal(aso.Read(1)): loop while p1=255 and not aso.EOSif p1>191 and p1<196 then exit do else aso.read(binval2(aso.Read(2))-2)do:p1=binVal(aso.Read(1)):loop while p1<255 and not aso.EOSloop while trueaso.Read(3)ret(0)="JPG"ret(2)=binval2(aso.Read(2))ret(1)=binval2(aso.Read(2))case else:if left(Bin2Str(bFlag),2)="BM" thenaso.Read(15)ret(0)="BMP"ret(1)=binval(aso.Read(4))ret(2)=binval(aso.Read(4))elseret(0)=""end ifend selectret(3)="width=""" & ret(1) &""" height="""& ret(2) &""""getimagesize=retEnd FunctionEnd Class%>将以上代码复制生成GPS.asp文件,这样无组件获取图片尺寸的通用类就OK了。
2.获取图片路径由于不只一张图片,以及图片需分类存放,我们在数据库中设计了一个存放图片相对路径的字段ImgURL。
我们把上传的图片都放在一个名为images的文件夹中(至于如何无组件上传图片心晴就不在多说了)。
现在我们先设计一个ShowImg.asp页面用来显示缩略图及相关信息。
具体设计如下:图片:图片格式:图片尺寸:图片大小:点击次数:下面,我们获取图片的绝对路径。
代码如下:<%'/////获取ShowImg.asp的绝对路径/////Dim curFilecurFile=Server.mappath(Request.servervariables("PATH_INFO"))Dim curfilename,filename'/////图片相对路径(存于数据库中)cufilename=rs("ImgURL")'/////因为ShowImg.asp与images在同一目录,所以我们用instrrev获取images的路径///// filename=left(curFile,instrrev(curFile,""))&cufilename'/////建立GPS类实体/////Dim GetPicSizeSet GetPicSize=new GPSSet fs=Server.CreateObject("Scripting.FileSystemObject")'/////获取图片类型/////Dim PicSuffixNamePicSuffixName=fs.GetExtensionName(filename)Dim PD '//Picture DimensionDim PWidth,PHeightSelect Case PicSuffixNameCase "gif","bmp","jpg","png":'/////调用GPS通用类中的GetImageSize函数获取图片尺寸/////PD=GetPicSize.GetImageSize(filename)PWidth=PD(1) '//获取图片宽度PHeight=PD(2) '//获取图片高度Case "swf"PD=GetPicSize.GetImageSize(filename)PWidth=PD(1) '//获取Flash宽度PHeight=PD(2) '//获取Flash高度Case ElseEnd SelectSet fs=NothingSet GetPicSize=Nothing%>将上面的代码复制到<body>的上面就OK了!当然,有人会说,获取路径不一定要用PATH_INFO,直接用server.mappath()不就可以了嘛,呵呵,萝卜青菜各有所爱,主要是我用PA TH_INFO可以实现FSO的一些功能而用server.mappath()没有搞定,所以一直使用这个。