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.}
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top