Thursday, 22 November 2018

Compressed the image size if size more then 5 mb



string _strfilepath = filepath + "/" + DocumentName + filename + Path.GetExtension(objfileobj.PostedFile.FileName);

   decimal size = Math.Round(((decimal)objfileobj.PostedFile.ContentLength / (decimal)1024), 2);

  if (size > 500)
                    {
                        Stream strm = objfileobj.PostedFile.InputStream;
                        Imagecompression.ReduceImageSize(strm, _strfilepath);  
                    }

 public static void ReduceImageSize(Stream sourcePath, string targetPath)
        {
            using (var image = System.Drawing.Image.FromStream(sourcePath))
            {
                double scaleFactor = 0.5;
                var newWidth = (int)(image.Width * scaleFactor);
                var newHeight = (int)(image.Height * scaleFactor);
                var thumbnailImg = new Bitmap(newWidth, newHeight);
                var thumbGraph = Graphics.FromImage(thumbnailImg);
                thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbGraph.DrawImage(image, imageRectangle);
                thumbnailImg.Save(targetPath, image.RawFormat);
            }
        }