base 64 string To image conversion with compression in asp.net

public bool Base64ToImage(string imgUrl, string img)
        {
            string fileName = imgUrl + ".png";
            bool Result = false;
            byte[] image = Convert.FromBase64String(img);

            string Imgpath = HttpContext.Current.Server.MapPath("~/Temp/") + fileName;
            try
            {
                System.IO.File.WriteAllBytes(Imgpath, image);
                Bitmap bmp1 = new Bitmap(HttpContext.Current.Server.MapPath("~/Temp/") + fileName);
                ImageCodecInfo jgpEncoder = 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(HttpContext.Current.Server.MapPath("~/AdvertisementImages/") + fileName, jgpEncoder, myEncoderParameters);
                bmp1.Dispose();

                DeleteImage(HttpContext.Current.Server.MapPath("~/Temp/") + fileName);
                Result = true;
            }
            catch (Exception ex)
            {
                Result = false;
            }

            return Result;
        }


private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

Comments

Popular posts from this blog

Image to base 64 conversion in asp.net