How to save base64 images from editor to server path.

Total Post:24

Points:170
Mvc 
 127  View(s)
Ratings:
Rate this:

i want to  save base64 images from editor to server path.

  1. Post:280

    Points:1994
    Re: How to save base64 images from editor to server path.

    Try to use it:

    [HttpPost, Authorize, ValidateInput(false)]
            public ActionResult Post(PostModel model, FormCollection form)
            {
                if (ModelState.IsValid)
                {
                  model.Content = FetchImgsFromSource(model.Content);
                  model.AuthorID = WebSecurity.CurrentUserId;
                  db.Article.Add(model);
                    return RedirectToAction("Index");
                }
                return View("Post", model);
            }         
    public static string FetchImgsFromSource(string htmlSource)
            {
                string mainContent = htmlSource;
                string fileExtn = string.Empty;
                try
                {
                    List<string> listOfImgdata = new List<string>();
                    string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
                    string toDayDate = DateTime.Now.ToString("ddMMMyyyy");
                    MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                    foreach (Match m in matchesImgSrc)
                    {
                        string href = m.Groups[1].Value;
                        listOfImgdata.Add(href);
                    }
                    foreach (var item in listOfImgdata)
                    {
                        var imageId = Guid.NewGuid().ToString();
                        if (!Directory.Exists(string.Format(System.Web.HttpContext.Current.Server.MapPath("~/Images/{0}"), toDayDate)))
                        {
                            Directory.CreateDirectory(string.Format(System.Web.HttpContext.Current.Server.MapPath("~/Images/{0}"), toDayDate));
                        }
                        var lowerCase = item.ToLower();
                        if (lowerCase.IndexOf("data:image/png;base64") != -1)
                            fileExtn = ".png";
                        else if (lowerCase.IndexOf("data:image/jpg;base64") != -1 || lowerCase.IndexOf("data:image/jpeg;base64") != -1)
                            fileExtn = ".jpg";
                        else if (lowerCase.IndexOf("data:image/gif;base64") != -1)
                            fileExtn = ".gif";
                        else if (lowerCase.IndexOf("data:image/bmp;base64") != -1)
                            fileExtn = ".bmp";
                        string filePath = string.Format(System.Web.HttpContext.Current.Server.MapPath("~/Images/{0}/{1}{2}"), toDayDate, imageId, fileExtn != "" ? fileExtn : ".png");
                        string tempFilePath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Images/TempImages/PreCompressImage{0}", fileExtn));

                        byte[] imageBytes = Convert.FromBase64String(item.Replace("data:image/png;base64,", string.Empty).Replace("data:image/jpeg;base64,", string.Empty).Replace("data:image/bmp;base64,", string.Empty).Replace("data:image/gif;base64,", string.Empty));
                        using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                        {
                            Image image = Image.FromStream(ms, true);
                            image.Save((fileExtn == ".png" || fileExtn == ".jpg" || fileExtn == ".bmp") ? tempFilePath : filePath);
                            if (fileExtn == ".png" || fileExtn == ".jpg" || fileExtn == ".bmp"){
                                VaryQualityLevel(filePath, tempFilePath);
                            }
                        }
                        htmlSource = htmlSource.Replace(item, string.Format("/Images/{0}/{1}{2}", toDayDate, imageId, fileExtn != "" ? fileExtn : ".png"));
                    }
                    return htmlSource;
                }
                catch (Exception ex)
                {
                    return mainContent;
                }
            }
            private static void VaryQualityLevel(string filePath, string tempFilePath)
            {
                Bitmap bmp1 = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(resolveVirtual(tempFilePath)));
                ImageCodecInfo jgpEncoder =ArticlesController.GetEncoder(ImageFormat.Jpeg);
                System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
                myEncoderParameters.Param[0] = myEncoderParameter;
                bmp1.Save(System.Web.HttpContext.Current.Server.MapPath(resolveVirtual(filePath)), jgpEncoder, myEncoderParameters);
                bmp1.Dispose();
            }
            public static string resolveVirtual(string physicalPath)
            {
                string url = physicalPath.Substring(System.Web.HttpContext.Current.Server.MapPath("~").Length).Replace('\\', '/').Insert(0, "~/");
                return (url);
            }
            private static ImageCodecInfo GetEncoder(ImageFormat format)
            {
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.FormatID == format.Guid)
                    {
                        return codec;
                    }
                }
                return null;
            }

    i hope it will help to you.


      Modified On Jul-28-2018 05:08:43 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!