About the author

Miron Abramson
Me
Software Engineer,
CTO at PixeliT
and .NET addicted for long time.
Open source projects:
MbCompression - Compression library

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014

Creative Commons License

Blog Flux Directory
Technology Blogs - Blog Top Sites

Cropping image using jQuery, Jcrop and ASP.NET

Letting the client cropping his images on the site was never an easy task. With jQuery and the plugin Jcrop by Deep Liquid it is easier than ever to do it in ASP.NET site. Here is how to do it:

First we need to include jQuery library,Jcrop script file & Jquery css file in the page. Then, we need to tell Jcrop wich element is our image to crop, and what method to be fire when we are changing the cropping area:

//
//  Initialize Jcrop
//
$(function() {
$('#theImage').Jcrop({
        onChange: showCoords,
        onSelect: showCoords
    });
});

//
//  Will fire every move of the cropping area
//
function showCoords(c) {
    $('#x1').val(c.x);
    $('#y1').val(c.y);
    $('#x2').val(c.x2);
    $('#y2').val(c.y2);
    $('#w').val(c.w);
    $('#h').val(c.h);
};

x1,y1,x2,y2 are inputs from where the code behind will read the values of the cropping area.

The code behind that will actualy crop the image:

 protected void btnCrop_Click(object sender, EventArgs e)
{
    int X1 = Convert.ToInt32(Request.Form["x1"]);
    int Y1 = Convert.ToInt32(Request["y1"]);
    int X2 = Convert.ToInt32(Request.Form["x2"]);
    int Y2 = Convert.ToInt32(Request.Form["y2"]);
    int X = System.Math.Min(X1, X2);
    int Y = System.Math.Min(Y1, Y2);
    int w = Convert.ToInt32(Request.Form["w"]);
    int h = Convert.ToInt32(Request.Form["h"]);

    // That can be any image (jpg,jpeg,png,gif) from anywhere in the server
    string originalFile = Server.MapPath("~/images/miautito.jpg");


    using (Image img = Image.FromFile(originalFile))
    {
        using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
        {
            _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
            using (Graphics _graphic = Graphics.FromImage(_bitmap))
            {
                _graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                _graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                _graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                _graphic.DrawImage(img, 0, 0, w, h);
                _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);

                string extension = Path.GetExtension(originalFile);
                string croppedFileName = Guid.NewGuid().ToString();
                string path = Server.MapPath("~/cropped/");


                // If the image is a gif file, change it into png
                if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                {
                    extension = ".png";
                }

                string newFullPathName = string.Concat(path, croppedFileName, extension);

                using (EncoderParameters encoderParameters = new EncoderParameters(1))
                {
                    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                    _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                }
            }
        }
    }
}

Method to find the right codec to save the image in the maximum quality:

/// <summary>
/// Find the right codec
/// </summary>
/// <param name="extension"></param>
/// <returns></returns>
public static ImageCodecInfo GetImageCodec(string extension)
{
    extension = extension.ToUpperInvariant();
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FilenameExtension.Contains(extension))
        {
            return codec;
        }
    }
    return codecs[1];
}

You can see some demos of the Jquery Here, and actual demo using the above code in here: ASP.NET Demo.

Complete working source is available in the link below:

Crop.zip (165.24 kb)

Currently rated 4.6 by 17 people

  • Currently 4.647059/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | C# | Client side | Server side
Posted by Miron on Monday, April 20, 2009 8:17 AM
Permalink | Comments (5) | Post RSSRSS comment feed

Related posts

Comments

DotNetKicks.com

Monday, April 20, 2009 9:00 AM

trackback

Trackback from DotNetKicks.com

Cropping image using jQuery, Jcrop and ASP.NET

Jared Roberts us

Tuesday, April 21, 2009 8:29 AM

Jared Roberts

really nice. keep these coming.

Peter

Wednesday, April 22, 2009 6:16 AM

Peter

I created an BlogEngine extension for cropping & resizing images with Jcrop. Check it out on stribny.name/.../blogenginenet-image-manipulation-enhancements

Jason us

Monday, June 08, 2009 2:08 AM

Jason

Nice. I may be using a form of this on a project coming up.

Thanks

Ömer Faruk ZORLU tr

Tuesday, September 22, 2009 1:40 AM

Ömer Faruk ZORLU

This article is using jcrop for asp.net (component).
www.omerfarukzorlu.com/.../...nent-with-JCrop.aspx