Crop a Picture using C#

Crop a Picture using C#
A function to which you can pass the picture that you want to crap and the coordinates, and it will return a cropped vesion of the picture as a byte stream.
1.using System;
2.using System.Drawing;
3.using System.Drawing.Drawing2D;
4.using System.Drawing.Imaging;
5.using System.IO;
6. 
7.public static byte[] CropPicture(byte[] imgFile, int targetW, int 
  targetH, int targetX, int targetY)
8.{
9.      Image imgPhoto = Image.FromStream(new MemoryStream(imgFile));
10.    Bitmap bmpPhoto = new Bitmap(targetW, targetH, 
PixelFormat.Format24bppRgb);
11.     bmpPhoto.SetResolution(80, 60);
12.        Graphics gfxPhoto = Graphics.FromImage(bmpPhoto);
13.        gfxPhoto.SmoothingMode = SmoothingMode.AntiAlias;
14.        gfxPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
15.       gfxPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
16.        gfxPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 
targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
17.        MemoryStream mm = new MemoryStream();
18.        bmpPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
19.        // Dispose of all the objects to prevent memory leaks
20.       imgPhoto.Dispose();
21.        bmpPhoto.Dispose();
22.        gfxPhoto.Dispose();
23.        return mm.GetBuffer();
24.}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top