asp.net生成缩略图及给原始图加水印的函数

2008-09-26 08:36:49 北京时间

在编写程序时大家经常遇到给图片生成缩略图以及给原始图片添加水印的问题,下面这个函数便是在.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;
}




发表评论

请文明参与讨论,禁止漫骂攻击。本站保留不刊登无关和不雅评论的权力。


用户名: 密码: 匿名

相关新闻
计算分页,嘿嘿一次搞定不用判断 以下为引用的内容: intNumPage
一般来说我们都是用 Hashtable 的 ContainsKey 方法来查找 Hasht
引言 随着现代科技日新月异的发展,作为新兴产业的嵌入式移动信
出于安全考虑,几乎每个动态网站都具备 IP 地址屏蔽功能,而网上
问: Service Unavailable 是什么意思啊?? 答: Service Unava

广告
© 2008 The Czz5 Company. All Rights Reserved. 关于我们 - 联系我们 - 广告业务 - 网站地图 - 版权声明 - 友情连接 - 网站投稿 - 致信编辑