查看: 1764|回复: 0

[ASP.NET教程] asp.net实现生成缩略图及给原始图加水印的方法示例

发表于 2018-1-3 08:00:01

本文实例讲述了asp.net实现生成缩略图及给原始图加水印的方法。分享给大家供大家参考,具体如下:

  1. using System.IO;
  2. using System.Drawing.Imaging;
  3. private void Button1_ServerClick(object sender, System.EventArgs e)
  4. {
  5. Graphics g=null;
  6. System.Drawing.Image upimage=null;
  7. System.Drawing.Image thumimg=null;
  8. System.Drawing.Image simage=null;
  9. Bitmap outputfile=null;
  10. try
  11. {
  12. string extension = Path.GetExtension(File1.PostedFile.FileName).ToUpper();
  13. string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
  14. string smallpath = Server.MapPath(".")+"/smallimg/";
  15. string bigpath = Server.MapPath(".")+"/bigimg/";
  16. int width,height,newwidth,newheight;
  17. System.Drawing.Image.GetThumbnailImageAbort callb =new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
  18. if(!Directory.Exists(smallpath))
  19. Directory.CreateDirectory(smallpath);
  20. if(!Directory.Exists(bigpath))
  21. Directory.CreateDirectory(bigpath);
  22. Stream upimgfile = File1.PostedFile.InputStream;
  23. string simagefile = Server.MapPath("a8logo.jpg"); //要加水印的文件
  24. simage=System.Drawing.Image.FromFile(simagefile);
  25. upimage= System.Drawing.Image.FromStream(upimgfile); //上传的图片
  26. width = upimage.Width;
  27. height = upimage.Height;
  28. if(width>height)
  29. {
  30. newwidth=200;
  31. newheight =(int)((double)height/(double)width * (double)newwidth);
  32. } else
  33. {
  34. newheight=200;
  35. newwidth=(int)((double)width/(double)height * (double)newheight);
  36. }
  37. thumimg = upimage.GetThumbnailImage(newwidth,newheight,callb,IntPtr.Zero);
  38. outputfile=new Bitmap(upimage);
  39. g=Graphics.FromImage(outputfile);
  40. g.DrawImage(simage,new Rectangle(upimage.Width-simage.Width,upimage.Height-simage.Height,upimage.Width,upimage.Height),0,0,upimage.Width,upimage.Height,GraphicsUnit.Pixel);
  41. string newpath = bigpath + filename + extension; //原始图路径
  42. string thumpath = smallpath + filename + extension; //缩略图路径
  43. outputfile.Save(newpath);
  44. thumimg.Save(thumpath);
  45. outputfile.Dispose();
  46. }
  47. catch(Exception ex)
  48. {
  49. throw ex;
  50. }
  51. finally
  52. {
  53. if(g!=null)
  54. g.Dispose();
  55. if(thumimg!=null)
  56. thumimg.Dispose();
  57. if(upimage!=null)
  58. upimage.Dispose();
  59. if(simage!=null)
  60. simage.Dispose();
  61. }
  62. }
  63. public bool ThumbnailCallback()
  64. {
  65. return false;
  66. }
复制代码

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net操作json技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

希望本文所述对大家asp.net程序设计有所帮助。



回复

使用道具 举报