Cropping images in ASP.NET is easy task to do if you use right tools. In this posting I will introduce how to crop images using Jcrop and System.Drawing namespace classes. What we are building is simple and user-friendly image cropping interface that also demonstrates some simple features of Jcrop. Believe me, your users will love it!
Jcrop is jQuery based library that brings crop margins selection to client side. Before starting you need two (free) JavaScript libraries:
After downloading them create new ASP.NET Web Application project and unpack those libraries to js directory. Also copy file js/Jcrop/css/Jcrop.gif to root folder of your project and add image you want to crop to same folder.
Expected result
As a first thing we will show image to user and some informative labels under image. And, of course, there is button for cropping.
You can see those values changing under image when you change the size or location of cropping are box.
When user clicks crop button then image will be cropped and shown to user. In our current case the result will be something like shown on following screenshot.
You can crop image again and again and again until you get the result you like.
Code
This is my ASP.NET form. I have to warn you that my JavaScript is written just to make it work and it needs some more cosmetics if you plan to use this code in real development. So, no hard feelings, okay?
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Crop.aspx.cs" Inherits="BlogExamples.Crop" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title></title>
<link rel="Stylesheet" type="text/css" href="js/Jcrop/css/jquery.Jcrop.css" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/Jcrop/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript">
var editorID = '<%= _imageEditor.ClientID %>';
jQuery(function () {
jQuery('#' + editorID).Jcrop({
onChange: showCoords,
onSelect: showCoords
});
});
function showCoords(c) {
var tdX = document.getElementById('tdX');
var tdY = document.getElementById('tdY');
var tdWidth = document.getElementById('tdWidth');
var tdHeight = document.getElementById('tdHeight');
tdX.innerHTML = c.x;
tdY.innerHTML = c.y;
tdWidth.innerHTML = c.w;
tdHeight.innerHTML = c.h;
var xField = document.getElementById('<%= _xField.ClientID %>');
var yField = document.getElementById('<%= _yField.ClientID %>');
var widthField = document.getElementById('<%= _widthField.ClientID %>');
var heightField = document.getElementById('<%= _heightField.ClientID %>');
xField.value = c.x;
yField.value = c.y;
widthField.value = c.w;
heightField.value = c.h;
}
</script>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Image runat="server" ID="_imageEditor" ImageUrl="MY_FILE.JPG" />
</div>
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td>x:</td>
<td id="tdX">-</td>
<td>y:</td>
<td id="tdY">-</td>
<td>width:</td>
<td id="tdWidth">-</td>
<td>height:</td>
<td id="tdHeight">-</td>
<td><asp:Button runat="server" ID="_cropCommand" onclick="_cropCommand_Click" Text="Crop" /></td>
</tr>
</table>
<input type="hidden" runat="server" id="_xField" />
<input type="hidden" runat="server" id="_yField" />
<input type="hidden" runat="server" id="_widthField" />
<input type="hidden" runat="server" id="_heightField" />
</form>
</body>
</html>
And here is code-behind file of my form. If you plan to use this code in real development then you must validate values of crop margins before using them with drawing methods. Also you need error handling and you have to make sure that all objects will be disposed correctly.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI;
namespace BlogExamples
{
public partial class Crop : Page
{
protected void _cropCommand_Click(object sender, EventArgs e)
{
var x = int.Parse(_xField.Value);
var y = int.Parse(_yField.Value);
var width = int.Parse(_widthField.Value);
var height = int.Parse(_heightField.Value);
using(var photo = Image.FromFile(Server.MapPath("MY_IMAGE.JPG")))
using (var result = new Bitmap(width, height, photo.PixelFormat))
{
result.SetResolution(
photo.HorizontalResolution,
photo.VerticalResolution);
using (var g = Graphics.FromImage(result))
{
g.InterpolationMode =
InterpolationMode.HighQualityBicubic;
g.DrawImage(photo,
new Rectangle(0, 0, width, height),
new Rectangle(x, y, width, height),
GraphicsUnit.Pixel);
photo.Dispose();
result.Save(Server.MapPath("MY_IMAGE.JPG"));
}
}
}
}
}
Well, that’s it. If you have any troubles running this code then please drop me a comment here and I will try to help you.
View Comments (16)
lol !
I'm writing a toturial like this, but you are faster than me :)
thanks for sharing ;)
why you are using : document.getElementById
you can use jQuery selectors.that make your code faster.
use this :
var tdX = $('#tdX');
var tdY = $('#tdY');
var tdWidth = $('#tdWidth');
var tdHeight = $('#tdHeight');
From MSDN:
"Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."
Thanks for feedback, guys :)
David, I am not creating ASP.NET service here but ASP.NET web application. I have read from some sources that System.Drawing namespace is not supported (by Microsoft) under ASP.NET but this far world practice has shown that you can use this namespace as long as you use resources reasonably.
Hi abhishek!
What is the format of file you are trying to crop?
Do you get exceptions?
Have you made modifications to code?
Thats was useful. I want to put validation that image size cannot go beyond specified range, also it cannot shrink beyond specified range. Any idea, how can i do that?
Nice one.. it worked for me as well.. Thanks do writing such good articles... :)
Thanks for the very nice story
This line var x = int.Parse(_xField.Value);
is giving error "input string was not in a correct format"
also pls tell me from where jQuery(function() and
function showCoords(c) functions are called.
'Image' is an ambiguous reference between 'System.Web.UI.WebControls.Image' and 'System.Drawing.Image'
thanks thanks and thanks a lot.............
You are a star , thnx sir :)
it's not working in the deployed sever whichis 2003 server. But it's working fine in local machine..
can i use it in mit licence?
Thank u for the code
I cropped using asp.net mvc
http://www.codingsack.com/2015/12/20/run-time-crop-images-with-asp-net-mvc-generic-handler/