Several Methods of Processing Pictures in C Background

  • 2021-11-13 02:25:23
  • OfStack

This article introduces several methods of how to process pictures in the background using c #. The specific code is as follows:

Type 1: Save the uploaded pictures directly to the local area


 var supportedTypes = new[] { "jpg", "jpeg", "png", "gif", "bmp" };
          var fileName = System.Web.HttpContext.Current.Request.Files[0].FileName;
          var fileExt = System.IO.Path.GetExtension(fileName).Substring(1);
          if (!supportedTypes.Contains(fileExt))
          {
            return Json(new { msg = -1 });
          }

          Random r = new Random();
          var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt;
          var filepath = Path.Combine(Server.MapPath("~/avatar/temp"), filename);
          head.SaveAs(filepath);

Type 2: Convert pictures to byte type


//filePath  Picture physical address 
FileStream fs = new FileStream(filepath, FileMode.Open);
          byte[] byData = new byte[fs.Length];
          fs.Read(byData, 0, byData.Length);
          fs.Close();

Type 3: Convert uploaded pictures to byte type


 HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];

        if ((file == null))
        {
          return Json(new { Success = false, Msg = " Failed to upload picture ", Path = "" });
        }
        else
        {
          System.Drawing.Image image = System.Drawing.Image.FromStream(file.InputStream);

          MemoryStream ms = new MemoryStream();
          image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

          byte[] byteData = new byte[ms.Length];
          ms.Position = 0;
          ms.Read(byteData, 0, byteData.Length);
          ms.Close();
          image.Dispose();

         
        }
      }


Related articles: