[C#] C# 通过ASHX保存上传的图片并制作高质量的缩略图 →→→→→进入此内容的聊天室

来自 , 2020-06-29, 写在 C#, 查看 130 次.
URL http://www.code666.cn/view/f08b7ac8
  1. <%@ WebHandler Language="C#" Class="UploadFile" Debug="true" %>
  2.  
  3. using System;
  4. using System.Web;
  5.  
  6. public class UploadFile : IHttpHandler
  7. {
  8.  
  9.   public void ProcessRequest(HttpContext context)
  10.   {
  11.     context.Response.ContentType = "text/plain";
  12.     HttpPostedFile f1 = context.Request.Files["f1"];
  13.     String fileExt = System.IO.Path.GetExtension(f1.FileName);
  14.     System.Drawing.Image image = System.Drawing.Image.FromStream(f1.InputStream);
  15.     int newWidth = 300, newHeight = 200;
  16.     if ((decimal)image.Width / image.Height > (decimal)newWidth / newHeight)
  17.     {
  18.       newHeight = Convert.ToInt32((decimal)image.Height * newWidth / image.Width);
  19.     }
  20.     else if ((decimal)image.Width / image.Height < (decimal)newWidth / newHeight)
  21.     {
  22.       newWidth = Convert.ToInt32((decimal)image.Width * newHeight / image.Height);
  23.     }
  24.     System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(newWidth, newHeight);
  25.     System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
  26.     g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  27.     g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  28.     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
  29.     System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, newWidth, newHeight);
  30.     g.DrawImage(image, rectDestination, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
  31.     bmp.Save(context.Server.MapPath("~/") + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt);
  32.     bmp.Dispose();
  33.     image.Dispose();
  34.     context.Response.Write("OK");
  35.   }
  36.  
  37.   public bool IsReusable
  38.   {
  39.     get
  40.     {
  41.       return false;
  42.     }
  43.   }
  44.  
  45. }
  46.  
  47.  
  48. //csharp/6892

回复 "C# 通过ASHX保存上传的图片并制作高质量的缩略图"

这儿你可以回复上面这条便签

captcha