Click here to Skip to main content
15,884,099 members
Articles / Web Development / ASP.NET
Tip/Trick

Cropping an Image from Center in .NET (ASP.NET or a .NET desktop app)

Rate me:
Please Sign up or sign in to vote.
4.92/5 (12 votes)
17 Nov 2013CPOL 33.7K   1.6K   7   6
This tip shows how to crop images at the center with desired width and height in .NET (ASP.NET, Windows Forms, WPF, etc.)

Introduction

At times, there is a need to crop images at the center. For example, you need to store equal size Avatar images for users, but do not want to force users to first crop their images. You can instead allow them to use images of any dimension but process them at the server side to create equal sized images (having Avatar of different sizes on a site does not seem that great an idea!). A more elaborate solution would be to allow the user to select the crop region, but for simple needs that's overkill and waste of user time.

For a live demo of this technique, visit this jigsaw puzzle site page, where you can see equally sized user Avatars.

The Code

And here is the code that saves the images (.jpg in this case, but you can use other supported formats if you so wished). The last parameter specifies the path where the cropped image will be saved on disk.

C#
public bool SaveCroppedImage(Image image, int maxWidth, int maxHeight, string filePath)
{
    ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders()
                             .Where(codecInfo => 
                             codecInfo.MimeType == "image/jpeg").First();
    Image finalImage = image;
    System.Drawing.Bitmap bitmap = null;
    try
    {
        int left = 0;
        int top = 0;
        int srcWidth = maxWidth;
        int srcHeight = maxHeight;
        bitmap = new System.Drawing.Bitmap(maxWidth, maxHeight);
        double croppedHeightToWidth = (double)maxHeight / maxWidth;
        double croppedWidthToHeight = (double)maxWidth / maxHeight;

        if (image.Width > image.Height)
        {
            srcWidth = (int)(Math.Round(image.Height * croppedWidthToHeight));
            if (srcWidth < image.Width)
            {
                srcHeight = image.Height;
                left = (image.Width - srcWidth) / 2;
            }
            else
            {
                srcHeight = (int)Math.Round(image.Height * ((double)image.Width/srcWidth));
                srcWidth = image.Width;
                top = (image.Height - srcHeight) / 2;
            }
        }
        else
        {
            srcHeight = (int)(Math.Round(image.Width * croppedHeightToWidth));
            if (srcHeight < image.Height)
            {
                srcWidth = image.Width;
                top = (image.Height - srcHeight) / 2;
            }
            else
            {
                srcWidth = (int)Math.Round(image.Width * ((double)image.Height / srcHeight));
                srcHeight = image.Height;
                left = (image.Width - srcWidth) / 2;
            }
        }                
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 
            new Rectangle(left, top, srcWidth, srcHeight), GraphicsUnit.Pixel);
        }
        finalImage = bitmap;
    }
    catch { }
    try
    {
        using (EncoderParameters encParams = new EncoderParameters(1))
        {
            encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)100);
            //quality should be in the range 
            //[0..100] .. 100 for max, 0 for min (0 best compression)
            finalImage.Save(filePath, jpgInfo, encParams);
            return true;
        }
    }
    catch { }
    if (bitmap != null)
    {
        bitmap.Dispose();
    }
    return false;
}  

Here's how an ASP.NET MVC Action method might call the above function:

C#
[HttpPost]
public ActionResult Upload(HttpPostedFileBase imageFile)
{
   SaveCroppedImage(Image.FromStream(imageFile.InputStream), 
   100, 100, @"C:\Temp\image.jpg");
   return View();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead https://mathiversity.com
Unknown
I am a full-stack developer. My skills include JavaScript, C#/.Net, MS Azure cloud etc. I love to work on complex programming tasks requiring deep analysis, planning and use of efficient algorithms and data structures.

Comments and Discussions

 
AnswerThank you very much! Pin
Member 101545331-Mar-15 16:35
Member 101545331-Mar-15 16:35 
GeneralRe: Thank you very much! Pin
Kashif_Imran4-Mar-15 20:31
Kashif_Imran4-Mar-15 20:31 
GeneralMy vote of 5 Pin
Sturms22-Jul-14 7:55
Sturms22-Jul-14 7:55 
GeneralRe: My vote of 5 Pin
Kashif_Imran22-Jul-14 9:35
Kashif_Imran22-Jul-14 9:35 
Questionimage saving Pin
hongdida1-Apr-14 17:37
hongdida1-Apr-14 17:37 
You said this allows them to use images of any dimension but process the image at the server side to create equal sized images, does that mean I can crop the image without disturbing the original image file?

By the way, you just mentioned the the code to save edited image to disk, do you support saving image to web server?
AnswerRe: image saving Pin
Kashif_Imran1-Apr-14 17:46
Kashif_Imran1-Apr-14 17:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.