Image cropping in C#


public static byte[] CropImage(string Img, int Width, int Height, int X, int Y)
{
            try
            {
                //Generate Image from specified Image file path
                //Img = file path
                System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Img);

                //Generate Bitmap with given Width and Height
                Bitmap bmp = new Bitmap(Width, Height);
               //Set Resolution of Bitmap
                bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);

                //Create Graphic for Bitmap
                Graphics Graphic = Graphics.FromImage(bmp);
                Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                //Draw image from Original image for above Graphic Object
                Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, Width, Height), X, Y, Width, Height, GraphicsUnit.Pixel);

                MemoryStream ms = new MemoryStream();
                //Save bitmap image to specified stream with specified format
                bmp.Save(ms, OriginalImage.RawFormat);
                OriginalImage.Dispose();

               //return image into byte array
                return ms.GetBuffer();
            }
            catch (Exception ex)
            {
                return null;
            }
}

Comments

Popular posts from this blog

Display image from byte array in ASP.NET MVC

Export excel and Pdf with Kendo UI MVC c#

Convert a color image to black and white image in C#