Wednesday, July 8, 2020

Resize Image Functions especially resize_image_thumb

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using ImageBlurFilter;

namespace NOBOLO.Library.Utilities
{
    public static class ResizeImage
    {
        public static string Resize_Image_Thumb_Transparent(string filePath, string newFilePath, string newImgName, int newWidth, int newHeight, bool IsTransparent = false)
        {
            string newImagePath;

            try
            {
                newImagePath = newFilePath + newImgName;

                Image imgPhoto = Image.FromFile(filePath);
                // Bitmap bmp2 = new Bitmap(filePath);
                // Color pixel = bmp2.GetPixel(0, 0);

                //Check for exif data to determin orientation of camera when photo was taken and rotate to what's expected
                if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    //LogHelper.CreateLog("0x112", ErrorType.User);

                    var prop = imgPhoto.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value, 0);
                        if (orientationExif == 8)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            //LogHelper.CreateLog("Rotate270FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 3)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            //LogHelper.CreateLog("Rotate180FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 6)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            //LogHelper.CreateLog("Rotate90FlipNone", ErrorType.User);
                        }
                    }
                }


                // Do not reszie image if its width is <= newWidth  ///
                //if (imgPhoto.Width <= newWidth)
                //{
                //    imgPhoto.Save(newImagePath);
                //    imgPhoto.Dispose();
                //    return newImgName;
                //}

               int sourceWidth, sourceHeight, sourceX, sourceY, destX, destY;
                double nPercent, nPercentW, nPercentH;
                sourceWidth = imgPhoto.Width;
                sourceHeight = imgPhoto.Height;
                sourceX = 0;
                sourceY = 0;
                destX = 0;
                destY = 0;

                nPercent = 0;
                nPercentW = 0;
                nPercentH = 0;

                // nPercentW = (Convert.ToDouble(newWidth) / Convert.ToDouble(sourceWidth));
                //nPercentH = (Convert.ToDouble(newHeight) / Convert.ToDouble(sourceHeight));

                nPercentW = ((float)newWidth / (float)sourceWidth);
                nPercentH = ((float)newHeight / (float)sourceHeight);

                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentH;
                }
                else
                {
                    nPercent = nPercentW;
                }



                //if (nPercentH < nPercentW)
                //{
                //    nPercent = nPercentW;
                //    destY = Convert.ToInt32((newHeight - (sourceHeight * nPercent)) / 2);
                //}
                //else
                //{
                //    nPercent = nPercentH;
                //    destX = Convert.ToInt32((newWidth - (sourceWidth * nPercent)) / 2);
                //}

                if (nPercent > 1)
                    nPercent = 1;

                int destWidth = (int)Math.Round(sourceWidth * nPercent);
                int destHeight = (int)Math.Round(sourceHeight * nPercent);


                System.Drawing.Image newImage = new System.Drawing.Bitmap(newWidth, newHeight);
                using (System.Drawing.Graphics graphicsHandle = System.Drawing.Graphics.FromImage(newImage))
                {
                    graphicsHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    graphicsHandle.InterpolationMode =
                               System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphicsHandle.DrawImage(imgPhoto, 0, 0, newWidth, newHeight);
                }

                newImage.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Png);
                newImage.Dispose();
                imgPhoto.Dispose();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return newImgName;
        }


        //testing not working
        public static string Resize_Image_Thumb_test(string path, string newFilePath,string newImgName,
                     /* note changed names */
                     int newWidth, int newHeight
                    )
        {
            string newImagePath;
            newImagePath = newFilePath + newImgName;

            Image image = Image.FromFile(path);
            int  sourceWidth = image.Width;
            int sourceHeight = image.Height;

            System.Drawing.Image thumbnail =
                new Bitmap(newWidth, newHeight); // changed parm names
            System.Drawing.Graphics graphic =
                         System.Drawing.Graphics.FromImage(thumbnail);

            graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphic.SmoothingMode = SmoothingMode.HighQuality;
            graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphic.CompositingQuality = CompositingQuality.HighQuality;

            /* ------------------ new code --------------- */

            // Figure out the ratio
            double ratioX = (double)newWidth / (double)sourceWidth;
            double ratioY = (double)newHeight / (double)sourceHeight;
            // use whichever multiplier is smaller
            double ratio = ratioX < ratioY ? ratioX : ratioY;

            // now we can get the new height and width
            int newHeight2 = Convert.ToInt32(sourceHeight * ratio);
            int newWidth2 = Convert.ToInt32(sourceWidth * ratio);

            // Now calculate the X,Y position of the upper-left corner 
            // (one of these will always be zero)
            int posX = Convert.ToInt32((newWidth - (sourceWidth * ratio)) / 2);
            int posY = Convert.ToInt32((newHeight - (sourceHeight * ratio)) / 2);

            graphic.Clear(Color.White); // white padding
            graphic.DrawImage(image, posX, posY, newWidth, newHeight);

            /* ------------- end new code ---------------- */

            System.Drawing.Imaging.ImageCodecInfo[] info =
                             ImageCodecInfo.GetImageEncoders();
            EncoderParameters encoderParameters;
            encoderParameters = new EncoderParameters(1);
            encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                             100L);
            thumbnail.Save(newFilePath, info[1],
                             encoderParameters);

            return newImagePath;
        }

        //testing Fixed Size
        public static string Resize_Image_Thumb_fixed(string path, string newFilePath, string newImgName,
                     /* note changed names */
                     int newWidth, int newHeight, bool needToFill=true)
        {

            string newImagePath;

            try
            { 
            newImagePath = newFilePath + newImgName;

            Image image = Image.FromFile(path);

                //Check for exif data to determin orientation of camera when photo was taken and rotate to what's expected
                if (image.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    //LogHelper.CreateLog("0x112", ErrorType.User);

                    var prop = image.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(image.GetPropertyItem(0x112).Value, 0);
                        if (orientationExif == 8)
                        {
                            image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            //LogHelper.CreateLog("Rotate270FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 3)
                        {
                            image.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            //LogHelper.CreateLog("Rotate180FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 6)
                        {
                            image.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            //LogHelper.CreateLog("Rotate90FlipNone", ErrorType.User);
                        }
                    }
                }


             int sourceWidth = image.Width;
            int sourceHeight = image.Height;

           
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)newWidth / (float)sourceWidth);
            nPercentH = ((float)newHeight / (float)sourceHeight);
            if (!needToFill)
            {
                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentH;
                }
                else
                {
                    nPercent = nPercentW;
                }
            }
            else
            {
                if (nPercentH > nPercentW)
                {
                    nPercent = nPercentH;
                    destX = (int)Math.Round((newWidth -
                    (sourceWidth * nPercent)) / 2);
                }
                else
                {
                    nPercent = nPercentW;
                    destY = (int)Math.Round((newHeight -
                    (sourceHeight * nPercent)) / 2);
                }
            }

            if (nPercent > 1)
                nPercent = 1;

            int destWidth = (int)Math.Round(sourceWidth * nPercent);
            int destHeight = (int)Math.Round(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(
            destWidth <= newWidth ? destWidth : newWidth,
            destHeight < newHeight ? destHeight : newHeight,
            PixelFormat.Format32bppRgb);

            Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);
            grPhoto.Clear(System.Drawing.Color.White);
            grPhoto.InterpolationMode = InterpolationMode.Default;
            grPhoto.CompositingQuality = CompositingQuality.HighQuality;
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;

            grPhoto.DrawImage(image,
            new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),
            new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            System.Drawing.GraphicsUnit.Pixel);

            bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
            grPhoto.Dispose();

        }
            catch (Exception exp)
            {
                throw exp;
            }
            return newImgName;
        }


        public static string Resize_Image_Thumb(string filePath, string newFilePath, string newImgName, int newWidth, int newHeight)
        {
            string newImagePath;

            try
            {
                newImagePath = newFilePath + newImgName;

                Image imgPhoto = Image.FromFile(filePath);


                //Check for exif data to determin orientation of camera when photo was taken and rotate to what's expected
                if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    //LogHelper.CreateLog("0x112", ErrorType.User);

                    var prop = imgPhoto.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value, 0);
                        if (orientationExif == 8)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            //LogHelper.CreateLog("Rotate270FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 3)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            //LogHelper.CreateLog("Rotate180FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 6)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            //LogHelper.CreateLog("Rotate90FlipNone", ErrorType.User);
                        }
                    }
                }


                // Do not reszie image if its width is <= newWidth  ///
                if (imgPhoto.Width <= newWidth)
                {
                    imgPhoto.Save(newImagePath);
                    imgPhoto.Dispose();
                    return newImgName;
                }

                int sourceWidth, sourceHeight, sourceX, sourceY, destX, destY;
                double nPercent, nPercentW, nPercentH;
                sourceWidth = imgPhoto.Width;
                sourceHeight = imgPhoto.Height;
                sourceX = 0;
                sourceY = 0;
                destX = 0;
                destY = 0;

                nPercent = 0;
                nPercentW = 0;
                nPercentH = 0;

                // nPercentW = (Convert.ToDouble(newWidth) / Convert.ToDouble(sourceWidth));
                //nPercentH = (Convert.ToDouble(newHeight) / Convert.ToDouble(sourceHeight));

                nPercentW = ((float)newWidth / (float)sourceWidth);
                nPercentH = ((float)newHeight / (float)sourceHeight);

                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentH;
                }
                else
                {
                    nPercent = nPercentW;
                }



                //if (nPercentH < nPercentW)
                //{
                //    nPercent = nPercentW;
                //    destY = Convert.ToInt32((newHeight - (sourceHeight * nPercent)) / 2);
                //}
                //else
                //{
                //    nPercent = nPercentH;
                //    destX = Convert.ToInt32((newWidth - (sourceWidth * nPercent)) / 2);
                //}

                if (nPercent > 1)
                    nPercent = 1;

                int destWidth = (int)Math.Round(sourceWidth * nPercent);
                int destHeight = (int)Math.Round(sourceHeight * nPercent);


                //  int destWidth, destHeight;
                // destWidth = Convert.ToInt32(sourceWidth * nPercent);
                //destHeight = Convert.ToInt32(sourceHeight * nPercent);

                // Bitmap bmPhoto;
                //bmPhoto = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                Bitmap bmPhoto = new Bitmap(
       destWidth <= newWidth ? destWidth : newWidth,
       destHeight < newHeight ? destHeight : newHeight,
       PixelFormat.Format32bppRgb);

                //bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
                //Graphics grPhoto;
                //grPhoto = Graphics.FromImage(bmPhoto);
                //grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

                //grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
                Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);
                grPhoto.Clear(System.Drawing.Color.White);
                grPhoto.InterpolationMode = InterpolationMode.Default;
                grPhoto.CompositingQuality = CompositingQuality.HighQuality;
                grPhoto.SmoothingMode = SmoothingMode.HighQuality;

                grPhoto.DrawImage(imgPhoto,
                new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),
                new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                System.Drawing.GraphicsUnit.Pixel);

                grPhoto.Dispose();

                bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmPhoto.Dispose();

                imgPhoto.Dispose();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return newImgName;
        }

        public static string ScaleImage(string filePath, string newFilePath, string newImgName, int maxWidth, int maxHeight, bool needToFill = true)
        {
            string newImagePath;

            try
            {

                var bmp = new Bitmap(maxWidth, maxHeight);
                newImagePath = newFilePath + newImgName;

                Image imgPhoto = Image.FromFile(filePath);

                //Check for exif data to determin orientation of camera when photo was taken and rotate to what's expected
                if (imgPhoto.PropertyIdList.Contains(0x112)) //0x112 = Orientation
                {
                    //LogHelper.CreateLog("0x112", ErrorType.User);

                    var prop = imgPhoto.GetPropertyItem(0x112);
                    if (prop.Type == 3 && prop.Len == 2)
                    {
                        UInt16 orientationExif = BitConverter.ToUInt16(imgPhoto.GetPropertyItem(0x112).Value, 0);
                        if (orientationExif == 8)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            //LogHelper.CreateLog("Rotate270FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 3)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            //LogHelper.CreateLog("Rotate180FlipNone", ErrorType.User);
                        }
                        else if (orientationExif == 6)
                        {
                            imgPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone);
                            //LogHelper.CreateLog("Rotate90FlipNone", ErrorType.User);
                        }
                    }
                }


                var ratioX = (double)maxWidth / imgPhoto.Width;
                var ratioY = (double)maxHeight / imgPhoto.Height;
                var ratio = Math.Min(ratioX, ratioY);

                var newWidth = (int)(imgPhoto.Width * ratio);
                var newHeight = (int)(imgPhoto.Height * ratio);

                var newImage = new Bitmap(newWidth, newHeight);

                using (var graphics = Graphics.FromImage(bmp))
                    graphics.DrawImage(imgPhoto, 0, 0, newWidth, newHeight);

                bmp.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmp.Dispose();

                //Image imgPhoto = Image.FromFile(filePath);
                //newImagePath = newFilePath + newImgName;

                //int sourceWidth = imgPhoto.Width;
                //int sourceHeight = imgPhoto.Height;
                //int sourceX = 0;
                //int sourceY = 0;
                //int destX = 0;
                //int destY = 0;

                //float nPercent = 0;
                //float nPercentW = 0;
                //float nPercentH = 0;

                //nPercentW = ((float)maxWidth / (float)sourceWidth);
                //nPercentH = ((float)maxHeight / (float)sourceHeight);
                //if (!needToFill)
                //{
                //    if (nPercentH < nPercentW)
                //    {
                //        nPercent = nPercentH;
                //    }
                //    else
                //    {
                //        nPercent = nPercentW;
                //    }
                //}
                //else
                //{
                //    if (nPercentH > nPercentW)
                //    {
                //        nPercent = nPercentH;
                //        destX = (int)Math.Round((maxWidth -
                //        (sourceWidth * nPercent)) / 2);
                //    }
                //    else
                //    {
                //        nPercent = nPercentW;
                //        destY = (int)Math.Round((maxHeight -
                //        (sourceHeight * nPercent)) / 2);
                //    }
                //}

                //if (nPercent > 1)
                //    nPercent = 1;

                //int destWidth = (int)Math.Round(sourceWidth * nPercent);
                //int destHeight = (int)Math.Round(sourceHeight * nPercent);

                //Bitmap bmPhoto = new Bitmap(
                //destWidth <= maxWidth ? destWidth : maxWidth,
                //destHeight < maxHeight ? destHeight : maxHeight,
                //PixelFormat.Format32bppRgb);

                //Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);
                //grPhoto.Clear(System.Drawing.Color.White);
                //grPhoto.InterpolationMode = InterpolationMode.Default;
                //grPhoto.CompositingQuality = CompositingQuality.HighQuality;
                //grPhoto.SmoothingMode = SmoothingMode.HighQuality;

                //grPhoto.DrawImage(imgPhoto,
                //new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),
                //new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                //System.Drawing.GraphicsUnit.Pixel);

                //bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                //grPhoto.Dispose();
                //bmPhoto.Dispose();


            }
            catch
            {

            }
            return newImgName;
        }

        public static string CropAndResizeImage(string filePath, string newFilePath, string newImgName, int newWidth, int newHeight, int x1, int y1, int x2, int y2)
        {
            string newImagePath;

            try
            {
                var bmp = new Bitmap(newWidth, newHeight);

                newImagePath = newFilePath + newImgName;

                Image imgPhoto = Image.FromFile(filePath);

                Graphics g = Graphics.FromImage(bmp);

                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;

                int width = x2 - x1;
                int height = y2 - y1;

                g.DrawImage(imgPhoto, new Rectangle(0, 0, newWidth, newHeight), x1, y1, width, height, GraphicsUnit.Pixel);

                var memStream = new MemoryStream();

                bmp.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                bmp.Dispose();

                imgPhoto.Dispose();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return newImgName;
        }

        //string imageresizename = ResizeImage.CropImage(tempfilePath + strTempImageSave, newFilePath, "_R_" + strTempImageSave, 0, 200,600,400);
        public static string CropImage(string filePath, string newFilePath, string newImgName, int x1, int y1, int x2, int y2)
        {
            return CropAndResizeImage(filePath, newFilePath, newImgName, x2 - x1, y2 - y1, x1, y1, x2, y2);
        }

        public static string GetTempFilePath(bool flag)
        {
            if (flag == false)
            {
                //----Temparory SubDirectory Create
                if (!Directory.Exists(WebConfigurationManager.AppSettings["SiteImgPath"] + @"\" + "TempImages"))
                {
                    Directory.CreateDirectory(WebConfigurationManager.AppSettings["SiteImgPath"] + @"\" + "TempImages");
                }
            }
            else
            {
                Directory.Delete(WebConfigurationManager.AppSettings["SiteImgPath"] + @"\" + "TempImages", true);
            }

            return WebConfigurationManager.AppSettings["SiteImgPath"] + @"\" + "TempImages" + @"\";
        }

        public static string DownloadAndSaveTAC(string url, string fileName,string _userid)
        {
            string content = string.Empty;
            string _Filename = fileName + "_" + DateTime.UtcNow.ToString("MMddyyyy_hhmm") + ".html";

            using (WebClient client = new WebClient())
            {
                content = client.DownloadString(url);
                string path = WebConfigurationManager.AppSettings["SiteImgPath"] + @"\" + "TAC" + @"\"+ _userid + @"\";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                
                
                path = path+ _Filename;

                System.IO.File.WriteAllText(path, content);
            }

            return WebConfigurationManager.AppSettings["SiteImgURL"].ToString() + "/TAC/"+ _userid +"/" + _Filename;
        }


        public static System.Drawing.Image DownloadImageFromUrl(string imageUrl)
        {
            System.Drawing.Image image = null;

            try
            {
                System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(imageUrl);
                webRequest.AllowWriteStreamBuffering = true;
                webRequest.Timeout = 30000;

                System.Net.WebResponse webResponse = webRequest.GetResponse();

                System.IO.Stream stream = webResponse.GetResponseStream();

                image = System.Drawing.Image.FromStream(stream);

                webResponse.Close();
            }
#pragma warning disable CS0168 // The variable 'ex' is declared but never used
            catch (Exception ex)
#pragma warning restore CS0168 // The variable 'ex' is declared but never used
            {
                return null;
            }

            return image;
        }

        public static string Download_Image(string imageUrl)
        {
            try
            {
                System.Drawing.Image image = DownloadImageFromUrl(imageUrl);
                var filePath = GetTempFilePath(false);
                string rootPath = filePath;
                string newImageName = Guid.NewGuid().ToString() + ".png";
                string fileName = System.IO.Path.Combine(rootPath, newImageName);
                image.Save(fileName);
                return newImageName;
            }
            catch (Exception ex)
            {
                return ex.ToString();

            }
        }


        public static string Download_And_Crop_Image(byte[] imageBytes, string strFilename)
        {
            try
            {
                var filePath = GetTempFilePath(false);
                string rootPath = filePath;

                var ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                ms.Write(imageBytes, 0, imageBytes.Length);
                var image = new Bitmap(ms);


                //croping the unwanted white backgroun
                image = ImageProccesingTools.CropUnwantedBackground(image);

                rootPath = rootPath + strFilename;
                image.Save(rootPath, System.Drawing.Imaging.ImageFormat.Png);


                return rootPath;
            }
            catch (Exception ex)
            {
                return ex.ToString();

            }
        }

        //public static string Resize_Image_Thumb(string filePath, string newFilePath, string newImgName, int newWidth, int newHeight)
        //{
        //    string newImagePath;

        //    try
        //    {
        //        newImagePath = newFilePath + newImgName;

        //        Image imgPhoto = Image.FromFile(filePath);

        //        // Do not reszie image if its width is <= newWidth  ///
        //        if (imgPhoto.Width <= newWidth)
        //        {
        //            imgPhoto.Save(newImagePath);
        //            imgPhoto.Dispose();
        //            return newImgName;
        //        }

        //        int sourceWidth, sourceHeight, sourceX, sourceY, destX, destY;
        //        double nPercent, nPercentW, nPercentH;
        //        sourceWidth = imgPhoto.Width;
        //        sourceHeight = imgPhoto.Height;
        //        sourceX = 0;
        //        sourceY = 0;
        //        destX = 0;
        //        destY = 0;

        //        nPercent = 0;
        //        nPercentW = 0;
        //        nPercentH = 0;

        //        nPercentW = (Convert.ToDouble(newWidth) / Convert.ToDouble(sourceWidth));
        //        nPercentH = (Convert.ToDouble(newHeight) / Convert.ToDouble(sourceHeight));

        //        if (nPercentH < nPercentW)
        //        {
        //            nPercent = nPercentW;
        //            destY = Convert.ToInt32((newHeight - (sourceHeight * nPercent)) / 2);
        //        }
        //        else
        //        {
        //            nPercent = nPercentH;
        //            destX = Convert.ToInt32((newWidth - (sourceWidth * nPercent)) / 2);
        //        }

        //        int destWidth, destHeight;
        //        destWidth = Convert.ToInt32(sourceWidth * nPercent);
        //        destHeight = Convert.ToInt32(sourceHeight * nPercent);

        //        Bitmap bmPhoto;
        //        bmPhoto = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

        //        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
        //        Graphics grPhoto;
        //        grPhoto = Graphics.FromImage(bmPhoto);
        //        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        //        grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);

        //        grPhoto.Dispose();

        //        bmPhoto.Save(newImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        //        bmPhoto.Dispose();

        //        imgPhoto.Dispose();
        //    }
        //    catch (Exception exp)
        //    {
        //        throw exp;
        //    }
        //    return newImgName;
        //}


        public static string Get_BlurImage(string _TempImage, string _NewImagePath, ImageBlurFilter.ExtBitmap.BlurType _BlurType)
        {
            System.Drawing.Bitmap selectedSource = null;
            Bitmap bitmapResult = null;

            System.IO.StreamReader streamReader = new System.IO.StreamReader(_TempImage);
            selectedSource = (Bitmap)Bitmap.FromStream(streamReader.BaseStream);
            streamReader.Close();

            ImageBlurFilter.ExtBitmap.BlurType blurType = _BlurType;
            bitmapResult = selectedSource.ImageBlurFilter(blurType);


            string fileExtension = System.IO.Path.GetExtension(_TempImage).ToUpper();
            System.Drawing.Imaging.ImageFormat imgFormat = System.Drawing.Imaging.ImageFormat.Png;

            if (fileExtension == "BMP")
            {
                imgFormat = System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if (fileExtension == "JPG")
            {
                imgFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if (fileExtension == "PNG")
            {
                imgFormat = System.Drawing.Imaging.ImageFormat.Png;
            }

            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(_NewImagePath + "_Blur_" + System.IO.Path.GetFileName(_TempImage), false);
            bitmapResult.Save(streamWriter.BaseStream, imgFormat);
            streamWriter.Flush();
            streamWriter.Close();

            bitmapResult = null;
            return "_Blur_" + System.IO.Path.GetFileName(_TempImage);

        }


        public static string ImageToBase64(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }

    }


    static class ImageProccesingTools
    {


        //usage  //image = ImageProccesingTools.CropUnwantedBackground(image);

        public static Bitmap CropUnwantedBackground(Bitmap bmpOriginal)
        {
            // Getting The Background Color by checking Corners of Original Image

            Color baseColor = bmpOriginal.GetPixel(0, 0);

            //LogHelper.CreateLog("R= "+baseColor.R.ToString() + " G="+ baseColor.G.ToString() + " B="+ baseColor.B.ToString());
            //LogHelper.CreateLog("imageOHeight= " + bmpOriginal.Height.ToString() + " imageOWidth=" + bmpOriginal.Width.ToString());


            int SameCorners = 0;
            bool hasBaseColor = false;

            Point[] Corners = new Point[]{new Point(0,0),
                new Point(0,bmpOriginal.Height-1),
                new Point(bmpOriginal.Width-1,0),
                new Point(bmpOriginal.Width-1,bmpOriginal.Height-1)};

            for (int i = 0; i < 4; i++)
            {
                SameCorners = 0;
                baseColor = bmpOriginal.GetPixel(Corners[i].X, Corners[i].Y);
                for (int j = 0; j < 4; j++)
                {
                    Color CornerColor = bmpOriginal.GetPixel(Corners[j].X, Corners[j].Y);
                    if ((CornerColor.R <= baseColor.R * 1.1 && CornerColor.R >= baseColor.R * 0.9) &&
                        (CornerColor.G <= baseColor.G * 1.1 && CornerColor.G >= baseColor.G * 0.9) &&
                        (CornerColor.B <= baseColor.B * 1.1 && CornerColor.B >= baseColor.B * 0.9))
                    {
                        SameCorners++;
                    }
                }
                if (SameCorners > 2)
                {
                    hasBaseColor = true;
                    break;
                }
            }

            //--------------------------------------------------------------------
            // Finding the Bounds of Crop Area bu using Unsafe Code and Image Proccesing
            // keep in mind in BitmapData Pixel Format is BGR NOT RGB !!!!!!

            if (hasBaseColor)
            {

                int width = bmpOriginal.Width, height = bmpOriginal.Height;
                bool UpperLeftPointFounded = false;
                Point[] bounds = new Point[2];
                Color c;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        c = bmpOriginal.GetPixel(x, y);
                        bool sameAsBackColor = ((c.R <= baseColor.R * 1.1 && c.R >= baseColor.R * 0.9) &&
                                                (c.G <= baseColor.G * 1.1 && c.G >= baseColor.G * 0.9) &&
                                                (c.B <= baseColor.B * 1.1 && c.B >= baseColor.B * 0.9) &&
                                                (c.A <= baseColor.A * 1.1 && c.A >= baseColor.A * 0.9));
                        if (!sameAsBackColor)
                        {
                            if (!UpperLeftPointFounded)
                            {
                                bounds[0] = new Point(x, y);
                                bounds[1] = new Point(x, y);
                                UpperLeftPointFounded = true;
                            }
                            else
                            {
                                if (x > bounds[1].X)
                                    bounds[1].X = x;
                                else if (x < bounds[0].X)
                                    bounds[0].X = x;

                                if (y >= bounds[1].Y)
                                    bounds[1].Y = y;

                            }
                        }
                    }
                }
                //Int32 _w = bounds[1].X - bounds[0].X + 1;
                //Int32 _h = bounds[1].Y - bounds[0].Y + 1;


                Bitmap result = new Bitmap(bounds[1].X - bounds[0].X + 1, bounds[1].Y - bounds[0].Y + 1);
                Graphics g = Graphics.FromImage(result);
                g.DrawImage(bmpOriginal, new Rectangle(0, 0, result.Width, result.Height), new Rectangle(bounds[0].X, bounds[0].Y, bounds[1].X - bounds[0].X + 1, bounds[1].Y - bounds[0].Y + 1), GraphicsUnit.Pixel);
                return result;
            }
            else
            {
                return null;
            }
        }
    }

}

No comments:

Post a Comment

Two Factor Authentication using .Net Core

Install Package dotnet add package GoogleAuthenticator --version 3.1.1 Model Changes public bool IsAuthenticatorReset { get; set; } public s...