Click here to Skip to main content
14,660,457 members
Articles » Desktop Development » Miscellaneous » General
Tip/Trick
Posted 17 Nov 2013

Tagged as

Stats

28K views
1.5K downloads
7 bookmarked

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

Rate this:
4.92 (12 votes)
Please Sign up or sign in to vote.
4.92 (12 votes)
17 Nov 2013CPOL
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.

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:

[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)

Share

About the Author

Kashif_Imran
Technical Lead
Pakistan Pakistan
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
MemberMember 101545331-Mar-15 16:35 
GeneralRe: Thank you very much! Pin
Kashif_Imran4-Mar-15 20:31
MemberKashif_Imran4-Mar-15 20:31 
GeneralMy vote of 5 Pin
Sturms22-Jul-14 7:55
MemberSturms22-Jul-14 7:55 
GeneralRe: My vote of 5 Pin
Kashif_Imran22-Jul-14 9:35
MemberKashif_Imran22-Jul-14 9:35 
Questionimage saving Pin
hongdida1-Apr-14 17:37
Memberhongdida1-Apr-14 17:37 
AnswerRe: image saving Pin
Kashif_Imran1-Apr-14 17:46
MemberKashif_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.