Monday, December 7, 2015

Image cropping in C#

public static byte[] CropImage(string Img, int Width, int Height, int X, int Y)
                //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);

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

No comments:

Post a Comment