Wednesday, 9 March 2016

MVC- upload and Save Images in folder and convert as a String (Images to Base64String) and (Base64String to Images)

MVC- upload and Save Images folderand convert as a String (Images to Base64String) and (Base64String to Images)

Step1: index.cshtml

  @using (Html.BeginForm("UserRegister", "UserRegistration", FormMethod.Post, new { enctype = "multipart/form-data", @class = "msform", role = "form" }))
                    {
                        <div class="col-md-6 col-md-offset-3">
                        <center><div id="dvPreview" name="dvPreview" class="prw"><img id="imgPreview" name="imgPreview" src="~/images/Browse.png" style="padding: 10px;border-radius: 100%;margin-bottom: 20px;" /></div></center>
                        <input type="file" id="img" name="img" />
                        <center><input type="submit" id="btnSubmit" value="Next" class="next action-button" /> </center>  </div>
                    }

step2: controller.cs
using System.Drawing.Imaging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;


 public ActionResult UserRegister(HttpPostedFileBase img)
        {
            if (ModelState.IsValid)
            {
                if (img == null)
                {
                    ModelState.AddModelError("File", "Please Upload Your file");
                }
                else if (img.ContentLength > 0)
                {
                    int MaxContentLength = 1024 * 1024 * 3; //3 MB
                    string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".PNG", ".JPG", ".GIF" };

                    if (!AllowedFileExtensions.Contains(img.FileName.Substring(img.FileName.LastIndexOf('.'))))
                    {
                        ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                    }

                    else if (img.ContentLength > MaxContentLength)
                    {
                        ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                    }
                    else
                    {
                        if (Request.Files.Count > 0)
                        {
                            if (Request.Files[0].ContentLength > 0)
                            {
                               string filename = System.IO.Path.GetFileName(Request.Files[0].FileName);
                                string strLocation = HttpContext.Server.MapPath("~/images/UserProfile");
                                Request.Files[0].SaveAs(strLocation + @"\" + filename.Replace('+', '_'));
                                string imgContentType = filename.Substring(img.FileName.LastIndexOf('.')).Trim('.');
                                System.Drawing.Image image = System.Drawing.Image.FromFile(strLocation + @"\" + filename);
                                var imageFormatConverter = new ImageFormatConverter();
                                var imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(imgContentType);
                                Session["Image"] = ImageToBase64(image, imageFormat);
                                Array.ForEach(Directory.GetFiles(strLocation), System.IO.File.Delete);                             }
                        }
                    }
                }
            }
            return RedirectToAction("UserRegisterStep2", "UserRegistration");
        }

1. Images to Base64String







 public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //First Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();
                //Then Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

2. Base64String To Images
 



 public Image Base64ToImage(string base64String)
        {
            base64String = Session["Image"].ToString();
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image ProfilePic = Image.FromStream(ms, true);
            return ProfilePic;
        }

Display Images 
controller.cs

 if (lstModel.UserPicture != "" && lstModel.UserPicture != null)
                            {
                                byte[] decode = Convert.FromBase64String(lstModel.UserPicture);
                                MemoryStream ms = new System.IO.MemoryStream(decode);
                                Image img = System.Drawing.Image.FromStream(ms);
                                if (ImageFormat.Jpeg.Equals(img.RawFormat))
                                {
                                    var som = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(decode));
                                    Session["UserPicture"] = som;
                                }
                                else if (ImageFormat.Png.Equals(img.RawFormat))
                                {
                                    var som = String.Format("data:image/png;base64,{0}", Convert.ToBase64String(decode));
                                    Session["UserPicture"] = som;
                                }
                                else if (ImageFormat.Gif.Equals(img.RawFormat))
                                {
                                    var som = String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(decode));
                                    Session["UserPicture"] = som;
                                }
                                else if (ImageFormat.Bmp.Equals(img.RawFormat))
                                {
                                    var som = String.Format("data:image/bmp;base64,{0}", Convert.ToBase64String(decode));
                                    Session["UserPicture"] = som;
                                }
                            }



Index.cshtml

 <div id="imgpic" class="imgusrpic" name="dvPreview">
                                                <img id="imgPreview" name="imgPreview" src=@Session["UserPicture"] title="UserPicture" />
                                            </div> 

 

No comments: