在编写程序时大家经常遇到给图片生成缩略图以及给原始图片添加水印的问题,下面这个函数便是在.NET中给图片生成缩略图及给原始图片添加水印的。
usingSystem.IO; usingSystem.Drawing.Imaging;
privatevoidButton1_ServerClick(objectsender,System.EventArgse) { Graphicsg=null; System.Drawing.Imageupimage=null; System.Drawing.Imagethumimg=null; System.Drawing.Imagesimage=null; Bitmapoutputfile=null; try { stringextension=Path.GetExtension(File1.PostedFile.FileName).ToUpper(); stringfilename=DateTime.Now.ToString("yyyyMMddhhmmss"); stringsmallpath=Server.MapPath(".")+"/smallimg/"; stringbigpath=Server.MapPath(".")+"/bigimg/"; intwidth,height,newwidth,newheight;
System.Drawing.Image.GetThumbnailImageAbortcallb=newSystem.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); if(!Directory.Exists(smallpath)) Directory.CreateDirectory(smallpath); if(!Directory.Exists(bigpath)) Directory.CreateDirectory(bigpath);
Streamupimgfile=File1.PostedFile.InputStream; stringsimagefile=Server.MapPath("a8logo.jpg");//要加水印的文件 simage=System.Drawing.Image.FromFile(simagefile); upimage=System.Drawing.Image.FromStream(upimgfile);//上传的图片
width=upimage.Width; height=upimage.Height; if(width>height) { newwidth=200; newheight=(int)((double)height/(double)width*(double)newwidth); } else { newheight=200; newwidth=(int)((double)width/(double)height*(double)newheight); } thumimg=upimage.GetThumbnailImage(newwidth,newheight,callb,IntPtr.Zero); outputfile=newBitmap(upimage); g=Graphics.FromImage(outputfile); g.DrawImage(simage,newRectangle(upimage.Width-simage.Width,upimage.Height-simage.Height,upimage.Width,upimage.Height),0,0,upimage.Width,upimage.Height,GraphicsUnit.Pixel);
stringnewpath=bigpath+filename+extension;//原始图路径 stringthumpath=smallpath+filename+extension;//缩略图路径 outputfile.Save(newpath); thumimg.Save(thumpath); outputfile.Dispose();
} catch(Exceptionex) { throwex; } finally { if(g!=null) g.Dispose(); if(thumimg!=null) thumimg.Dispose(); if(upimage!=null) upimage.Dispose(); if(simage!=null) simage.Dispose(); } } publicboolThumbnailCallback() { returnfalse; }
|