DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Crop Image With .NET

02.14.2006
| 41549 views |
  • submit to reddit
        using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

public static byte[] CropImageFile(byte[] imageFile, int targetW, int targetH, int targetX, int targetY)
{
    Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
    Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
    bmPhoto.SetResolution(72, 72);
    Graphics grPhoto = Graphics.FromImage(bmPhoto);
    grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
    grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
    grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel);
    // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
    MemoryStream mm = new MemoryStream();
    bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
    imgPhoto.Dispose();
    bmPhoto.Dispose();
    grPhoto.Dispose();
    return mm.GetBuffer();
}