Advertisement
hubert17

Upload and Display Image in ASP.NET Entity Framework

Aug 15th, 2017
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.78 KB | None | 0 0
  1. // *** Snippets ***
  2. // public byte[] Picture { get; set; }
  3. // <form action="/controller/create" method="post" enctype="multipart/form-data">
  4. // <input type="file" name="FileUpload" accept="image/*" />
  5. // [HttpPost]
  6. // public ActionResult Create(MyClass myObject, HttpPostedFileBase FileUpload)
  7. // myObject.Picture = Gabs.Helpers.ImageUtility.FileToByteArray(FileUpload);
  8. // <img src="data:image/jpg;base64,@Convert.ToBase64String(Model.Picture)" />
  9.  
  10. using System;
  11. using System.Drawing;
  12. using System.Drawing.Drawing2D;
  13. using System.IO;
  14.  
  15. namespace Gabs.Helpers
  16. {
  17.     public class ImageUploadUtil
  18.     {
  19.         private const int MAX_HEIGHT = 600; // height in pixel
  20.         private const bool QUALITY = true; // true = high quality, false = fast performance
  21.         public const string FOLDER = "ImageUpload"; // http://SERVER/FOLDER
  22.         public const string THUMBNAIL = "thumb"; // http://SERVER/FOLDER/THUMBNAIL
  23.         private const int THUMBNAIL_WIDTH = 200; // Assign 0 to disable
  24.         private const int THUMBNAIL_HEIGHT = 150; // Assign 0 to disable
  25.  
  26.         public static byte[] FileToByteArray(System.Web.HttpPostedFileBase File, int maxHeight, bool highQuality = QUALITY)
  27.         {
  28.             try
  29.             {
  30.                 if (File.ContentType.Contains("image"))
  31.                 {
  32.                     // Convert Uploaded File to byte array
  33.                     byte[] image = new byte[File.ContentLength];
  34.                     File.InputStream.Read(image, 0, File.ContentLength);
  35.                     return Resize(image, maxHeight, highQuality); // Resize and store as Jpeg
  36.                 }                
  37.             }
  38.             catch { }
  39.  
  40.             return null;
  41.         }
  42.  
  43.         public static byte[] FileToByteArray(System.Web.HttpPostedFileBase File, bool highQuality)
  44.         {
  45.             return FileToByteArray(File, MAX_HEIGHT, highQuality);
  46.         }
  47.  
  48.         public static byte[] FileToByteArray(System.Web.HttpPostedFileBase File)
  49.         {
  50.             return FileToByteArray(File, MAX_HEIGHT, QUALITY);
  51.         }
  52.  
  53.         public static string SaveToJpegFile(System.Web.HttpPostedFileBase File, string strFileName, string strFolder, int maxHeight = MAX_HEIGHT, bool highQuality = QUALITY)
  54.         {
  55.             try
  56.             {
  57.                 if (File.ContentType.Contains("image"))
  58.                 {
  59.                     var arrImageBytes = FileToByteArray(File, maxHeight, highQuality);
  60.  
  61.                     string folder = string.IsNullOrEmpty(strFolder) ? System.Web.HttpContext.Current.Server.MapPath("~/" + FOLDER) : System.Web.HttpContext.Current.Server.MapPath("~/" + strFolder);
  62.                     string filename = string.IsNullOrEmpty(strFileName) ? Path.GetFileNameWithoutExtension(File.FileName) : strFileName;
  63.                     string filenameExt = filename + "_" + GenerateUniqueChars() + ".jpg";
  64.                     string path = Path.Combine(folder, filenameExt);
  65.  
  66.                     System.IO.Directory.CreateDirectory(folder);
  67.                     System.IO.File.WriteAllBytes(path, arrImageBytes);
  68.  
  69.                     if (THUMBNAIL_HEIGHT > 0 && THUMBNAIL_WIDTH > 0)
  70.                     {
  71.                         Image image = Image.FromFile(path);
  72.                         Image thumb = FixedSize(image, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, true);
  73.                         folder = Path.Combine(folder, THUMBNAIL);
  74.                         System.IO.Directory.CreateDirectory(folder);
  75.                         path = Path.Combine(folder, filenameExt);
  76.                         thumb.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
  77.                     }
  78.  
  79.                     return filenameExt;
  80.                 }
  81.             }
  82.             catch (Exception ex)
  83.             {
  84.                 return ex.Message;
  85.             }
  86.  
  87.             return string.Empty;
  88.         }
  89.  
  90.         public static string SaveToJpegFile(System.Web.HttpPostedFileBase File, string strFileName, int maxHeight = MAX_HEIGHT, bool highQuality = QUALITY)
  91.         {
  92.             return SaveToJpegFile(File, strFileName, FOLDER, maxHeight, highQuality);
  93.         }
  94.  
  95.         public static string SaveToJpegFile(System.Web.HttpPostedFileBase File, int maxHeight, bool highQuality = QUALITY)
  96.         {
  97.             return SaveToJpegFile(File, string.Empty, FOLDER, maxHeight, highQuality);
  98.         }
  99.  
  100.         public static string SaveToJpegFile(System.Web.HttpPostedFileBase File, bool highQuality)
  101.         {
  102.             return SaveToJpegFile(File, string.Empty, FOLDER, MAX_HEIGHT, highQuality);
  103.         }
  104.  
  105.         public static string SaveToJpegFile(System.Web.HttpPostedFileBase File)
  106.         {
  107.             return SaveToJpegFile(File, string.Empty, FOLDER, MAX_HEIGHT, QUALITY);
  108.         }
  109.  
  110.         public static byte[] Resize(byte[] image, int maxHeight, bool highQuality = QUALITY)
  111.         {
  112.             MemoryStream stream = new MemoryStream(image);
  113.             Image img = Image.FromStream(stream);
  114.  
  115.             foreach (var prop in img.PropertyItems)
  116.             {
  117.                 //if ((prop.Id == 0x0112 || prop.Id == 5029 || prop.Id == 274))
  118.                 if (Array.IndexOf(img.PropertyIdList, 274) > -1)
  119.                 {
  120.                     var orientation = (int)img.GetPropertyItem(274).Value[0];
  121.                     img = OrientImage(img, orientation);
  122.                 }
  123.  
  124.                 img = ScaleImage(img, maxHeight, highQuality);
  125.  
  126.                 var ms = new MemoryStream();
  127.                 img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  128.                 image = ms.ToArray();
  129.             }
  130.  
  131.             return image;
  132.         }
  133.  
  134.         public static byte[] ResizeToThumbnail(byte[] image, int Width = THUMBNAIL_WIDTH, int Height = THUMBNAIL_HEIGHT, bool highQuality = false)
  135.         {
  136.             Image img;
  137.             using (var ms = new MemoryStream(image))
  138.             {
  139.                 img = Image.FromStream(ms);
  140.             }
  141.             var resizeImage = FixedSize(img, Width, Height, highQuality);
  142.             using (var ms = new MemoryStream())
  143.             {
  144.                 resizeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  145.                 return ms.ToArray();
  146.             }
  147.         }
  148.  
  149.         private static Image OrientImage(Image img, int orientation)
  150.         {
  151.             switch (orientation)
  152.             {
  153.                 case 1:
  154.                     // No rotation required.
  155.                     break;
  156.                 case 2:
  157.                     img.RotateFlip(RotateFlipType.RotateNoneFlipX);
  158.                     break;
  159.                 case 3:
  160.                     img.RotateFlip(RotateFlipType.Rotate180FlipNone);
  161.                     break;
  162.                 case 4:
  163.                     img.RotateFlip(RotateFlipType.Rotate180FlipX);
  164.                     break;
  165.                 case 5:
  166.                     img.RotateFlip(RotateFlipType.Rotate90FlipX);
  167.                     break;
  168.                 case 6:
  169.                     img.RotateFlip(RotateFlipType.Rotate90FlipNone);
  170.                     break;
  171.                 case 7:
  172.                     img.RotateFlip(RotateFlipType.Rotate270FlipX);
  173.                     break;
  174.                 case 8:
  175.                     img.RotateFlip(RotateFlipType.Rotate270FlipNone);
  176.                     break;
  177.             }
  178.  
  179.             // This EXIF data is now invalid and should be removed.
  180.             img.RemovePropertyItem(274);
  181.  
  182.             return img;
  183.         }
  184.  
  185.         private static Image ScaleImage(Image image, int maxHeight = MAX_HEIGHT, bool highQuality = QUALITY)
  186.         {
  187.             var ratio = (double)maxHeight / image.Height;
  188.             var newWidth = (int)(image.Width * ratio);
  189.             var newHeight = (int)(image.Height * ratio);
  190.             var newImage = new Bitmap(newWidth, newHeight);
  191.  
  192.             using (var g = Graphics.FromImage(newImage))
  193.             {
  194.                 if(highQuality)
  195.                 {
  196.                     g.CompositingQuality = CompositingQuality.HighQuality;
  197.                     g.SmoothingMode = SmoothingMode.HighQuality;
  198.                     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  199.                 }
  200.                 g.DrawImage(image, 0, 0, newWidth, newHeight);
  201.             }
  202.  
  203.             return newImage;
  204.         }
  205.  
  206.         private static Image FixedSize(Image image, int Width, int Height, bool needToFill)
  207.         {
  208.             #region calculations
  209.             int sourceWidth = image.Width;
  210.             int sourceHeight = image.Height;
  211.             int sourceX = 0;
  212.             int sourceY = 0;
  213.             double destX = 0;
  214.             double destY = 0;
  215.  
  216.             double nScale = 0;
  217.             double nScaleW = 0;
  218.             double nScaleH = 0;
  219.  
  220.             nScaleW = ((double)Width / (double)sourceWidth);
  221.             nScaleH = ((double)Height / (double)sourceHeight);
  222.             if (!needToFill)
  223.             {
  224.                 nScale = Math.Min(nScaleH, nScaleW);
  225.             }
  226.             else
  227.             {
  228.                 nScale = Math.Max(nScaleH, nScaleW);
  229.                 destY = (Height - sourceHeight * nScale) / 2;
  230.                 destX = (Width - sourceWidth * nScale) / 2;
  231.             }
  232.  
  233.             if (nScale > 1)
  234.                 nScale = 1;
  235.  
  236.             int destWidth = (int)Math.Round(sourceWidth * nScale);
  237.             int destHeight = (int)Math.Round(sourceHeight * nScale);
  238.             #endregion
  239.  
  240.             Bitmap bmPhoto = null;
  241.             try
  242.             {
  243.                 bmPhoto = new Bitmap(destWidth + (int)Math.Round(2 * destX), destHeight + (int)Math.Round(2 * destY));
  244.             }
  245.             catch (Exception ex)
  246.             {
  247.                 throw new ApplicationException(string.Format("destWidth:{0}, destX:{1}, destHeight:{2}, desxtY:{3}, Width:{4}, Height:{5}",
  248.                     destWidth, destX, destHeight, destY, Width, Height), ex);
  249.             }
  250.             using (Graphics grPhoto = Graphics.FromImage(bmPhoto))
  251.             {
  252.                 if(QUALITY == true)
  253.                 {
  254.                     grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
  255.                     grPhoto.CompositingQuality = CompositingQuality.HighQuality;
  256.                     grPhoto.SmoothingMode = SmoothingMode.HighQuality;
  257.                 }
  258.  
  259.                 Rectangle to = new Rectangle((int)Math.Round(destX), (int)Math.Round(destY), destWidth, destHeight);
  260.                 Rectangle from = new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight);
  261.                 grPhoto.DrawImage(image, to, from, GraphicsUnit.Pixel);
  262.  
  263.                 return bmPhoto;
  264.             }
  265.         }
  266.  
  267.         private static string GenerateUniqueChars()
  268.         {
  269.             char[] padding = { '=' };
  270.             return Convert.ToBase64String(Guid.NewGuid().ToByteArray()).TrimEnd(padding).Replace('+', '-').Replace('/', '_'); ;
  271.         }
  272.     }
  273. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement