现在的位置: 首页 > 综合 > 正文

ASP.NET(C#)图片上传压缩成缩略图的代码

2013年01月18日 ⁄ 综合 ⁄ 共 2172字 ⁄ 字号 评论关闭
 

  1. // 按模版比例生成缩略图(以流的方式获取源文件)
  2. //生成缩略图函数
  3. //顺序参数:源图文件流、缩略图存放地址、模版宽、模版高
  4. //注:缩略图大小控制在模版区域内
  5. public static void MakeSmallImg(System.IO.Stream fromFileStream,string fileSaveUrl,System.Double templateWidth,System.Double templateHeight)
  6. {
  7. //从文件取得图片对象,并使用流中嵌入的颜色管理信息
  8. System.Drawing.Image myImage = System.Drawing.Image.FromStream(fromFileStream,true);
  9. //缩略图宽、高
  10. System.Double newWidth = myImage.Width , newHeight = myImage.Height;
  11. //宽大于模版的横图
  12. if(myImage.Width>myImage.Height || myImage.Width==myImage.Height)
  13. {
  14. if(myImage.Width > templateWidth)
  15. {
  16. //宽按模版,高按比例缩放
  17. newWidth = templateWidth;
  18. newHeight = myImage.Height * (newWidth/myImage.Width);
  19. }
  20. }
  21. //高大于模版的竖图
  22. else
  23. {
  24. if(myImage.Height > templateHeight)
  25. {
  26. //高按模版,宽按比例缩放
  27. newHeight = templateHeight;
  28. newWidth = myImage.Width * (newHeight/myImage.Height);
  29. }
  30. }
  31. //取得图片大小
  32. System.Drawing.Size mySize = new Size((int)newWidth,(int)newHeight);
  33. //新建一个bmp图片
  34. System.Drawing.Image bitmap = new System.Drawing.Bitmap(mySize.Width,mySize.Height);
  35. //新建一个画板
  36. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
  37. //设置高质量插值法
  38. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  39. //设置高质量,低速度呈现平滑程度
  40. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  41. //清空一下画布
  42. g.Clear(Color.White);
  43. //在指定位置画图
  44. g.DrawImage(myImage , new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height) , 
  45. new System.Drawing.Rectangle(0, 0, myImage.Width,myImage.Height) , 
  46. System.Drawing.GraphicsUnit.Pixel);
  47. ///文字水印
  48. //System.Drawing.Graphics G=System.Drawing.Graphics.FromImage(bitmap);
  49. //System.Drawing.Font f=new Font("宋体",10);
  50. //System.Drawing.Brush b=new SolidBrush(Color.Black);
  51. //G.DrawString("myohmine",f,b,10,10);
  52. //G.Dispose();
  53. ///图片水印
  54. //System.Drawing.Image copyImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("pic/1.gif"));
  55. //Graphics a = Graphics.FromImage(bitmap);
  56. //a.DrawImage(copyImage, new Rectangle(bitmap.Width-copyImage.Width,bitmap.Height-copyImage.Height,copyImage.Width, copyImage.Height),0,0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
  57. //copyImage.Dispose();
  58. //a.Dispose();
  59. //copyImage.Dispose();
  60. //保存缩略图
  61. bitmap.Save(fileSaveUrl , System.Drawing.Imaging.ImageFormat.Jpeg);
  62. g.Dispose();
  63. myImage.Dispose();
  64. bitmap.Dispose();
  65. }

抱歉!评论已关闭.