After reading alot on the net in this article will let you know with the help of jqueries that how can we upload the image and crop it according to our choice like we do in orkut or in facebook. i just tried to do something similar. Well, first of all create folders name “images” which will keep the image for cropping and under images create “crop” name folder which will keep the proportionate cropped image files and last one create “Profile_pics” which will crop the proportionate cropped image once again and this one is optional you can remove that methods. In this article i have restricted the image size which is “200kb” only so you can increase it. Hope you will like this article.
*create a page “Default2.aspx”
Now, Copy paste the source code below.
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>
<!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>crop images asp.net</title>
<link href=”jquery.Jcrop.css” rel=”stylesheet” type=”text/css” /><script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js”></script>
<script src=”js/jquery.Jcrop.min.js” type=”text/javascript”></script>
<script type=”text/javascript”>
jQuery(function($){
// To hold the API and image size.
var jcrop_api, boundx, boundy;
$(‘#img_crop’).Jcrop({ // img_crop is the ID of image control
onChange: updatePreview, // will display the selected img on change.
onSelect: updatePreview, // will display the selected img Img_preview
onSelect: storeCoords, // will tell the coordinates
aspectRatio: 1
},function(){
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
});
function updatePreview(c)
{
if (parseInt(c.w) > 0)
{ var rx = 100 / c.w;
var ry = 100 / c.h;
$(‘#Img_preview’).css({ //Img_preview is the ID of image control
width: Math.round(rx * boundx) + ‘px’,
height: Math.round(ry * boundy) + ‘px’,
marginLeft: ‘-’ + Math.round(rx * c.x) + ‘px’,
marginTop: ‘-’ + Math.round(ry * c.y) + ‘px’ });
} }; });
// will store the selected part the images coordinates
function storeCoords(c) {
jQuery(‘#X’).val(c.x); // X of the hidden field
jQuery(‘#Y’).val(c.y); // Y of the hidden field
jQuery(‘#W’).val(c.w); // W of the hidden field
jQuery(‘#H’).val(c.h); // H of the hidden field
};
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Panel ID=”Panel_Upload” runat=”server”>
Select Image: <asp:FileUpload ID=”ProfilePic_Uploader” runat=”server” />
<asp:RegularExpressionValidator ID=”RegularExpressionValidator1″ runat=”server”
ControlToValidate=”ProfilePic_Uploader”
ErrorMessage=”Invalid File!(only .gif, .jpg, .jpeg, .wav Files are supported)”
ValidationExpression=”^.+(.jpg|.JPG|.gif|.GIF|.jpeg|JPEG)$”></asp:RegularExpressionValidator>
<br /> <br />
<asp:Button ID=”btn_upload” runat=”server” OnClick=”btn_upload_Click”
Text=”Upload image” />
<br />
</asp:Panel>
<asp:Panel ID=”Panel_Crop” runat=”server” Visible=”false”>
<asp:Image ID=”img_crop” runat=”server” />
<br />
<asp:HiddenField ID=”X” runat=”server” />
<asp:HiddenField ID=”Y” runat=”server” />
<asp:HiddenField ID=”W” runat=”server” />
<asp:HiddenField ID=”H” runat=”server” />
<asp:Button ID=”btn_crop” runat=”server” Text=”Crop” OnClick=”btn_crop_Click” />
<div style=”width:100px;height:100px;overflow:hidden;”>
<img ID=”Img_preview” runat=”server” alt=”Preview” src=”"/>
</div>
</asp:Panel>
<asp:Panel ID=”Panel_cropped” runat=”server” Visible=”false”>
<asp:Image ID=”img_cropped” runat=”server” />
</asp:Panel>
</div>
<p>
<asp:Label ID=”lbl_msg” runat=”server” />
</p>
</form>
</body>
</html>
OUTPUT
Now, copy and paste the Code-behind into your .cs page
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using System.Text;
using System.Drawing;
using System.Net.Mail;
using System.Text.RegularExpressions;
using System.Threading;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
System.Drawing.Image Thumbnail_img;
string Img_name;
// below will tell the path to save image in “images” folder . if you need to change then you can change it here.
string Images_path = HttpContext.Current.Request.PhysicalApplicationPath + “images\\”;
protected void btn_upload_Click(object sender, EventArgs e)
{
// will check the size of the image and here you can change it. Ii used 200Kb = 1024*200= 204800
if (ProfilePic_Uploader.PostedFile.ContentLength <= 204800)
{
//will keep the filename of the image.
ViewState["Image"] = ProfilePic_Uploader.FileName;
//will save the selected image into “images” name folder.
ProfilePic_Uploader.PostedFile.SaveAs(Images_path + ViewState["Image"]);
// will hide/unhide the panels.
Panel_Upload.Visible = false;
Panel_Crop.Visible = true;
// display the image from images folder after saving into it.
img_crop.ImageUrl = “images/” + ViewState["Image"].ToString();
Img_preview.Src = “images/” + ViewState["Image"].ToString();
}
else
lbl_msg.Text = “Image too large. Please upload image smaller than 200Kb.”;
}
protected void btn_crop_Click(object sender, EventArgs e)
{
// taking the image name form ViewState.
Img_name = ViewState["Image"].ToString();
// will assign the selected Coordinates of the image (these are the hidden variables).
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
// passing the image path with above values into Crop_Images
byte[] Crop_img = Crop_Image(Images_path + Img_name, w, h, x, y);
// create new instance of MemoryStream.
using (MemoryStream MS = new MemoryStream(Crop_img, 0, Crop_img.Length))
{
MS.Write(Crop_img, 0, Crop_img.Length);
using (System.Drawing.Image Cropped_Image = System.Drawing.Image.FromStream(MS, true))
{
// will save the cropped image into “images/crop/” folder
string Save_image_to = Server.MapPath(“images/crop/” + Img_name);
Cropped_Image.Save(Save_image_to, Cropped_Image.RawFormat);
Panel_Crop.Visible = false;
Panel_cropped.Visible = true;
// will display the cropped image.
ViewState["imgcrop"] = Img_name;
Img_preview.Src = “Profile_pics/” + Img_name;
}
}
System.Threading.Thread.Sleep(500);
// will call the following method.
MakeThumbnail();
// display the image after cropping the the cropped image .
//follwoing u can store the img inti your Database table
//********* START ***********//
////cmd = new SqlCommand(“Insertquery or update query”, con);
////cmd.Parameters.AddWithValue(“@image”, “imgname”);
////cmd.ExecuteNonQuery();
//********* END ***********//
img_cropped.ImageUrl = “Profile_pics/” + ViewState["new_img_name"].ToString();
}
//Getting the Crop_image values it Byte[]
static byte[] Crop_Image(string Img, int Width, int Height, int X, int Y)
{
// System.Drawing = System.Drawing;
try
{
using (System.Drawing.Image OriginalImage = System.Drawing.Image.FromFile(Img))
{
using (System.Drawing.Bitmap bmp_img = new System.Drawing.Bitmap(Width, Height))
{
bmp_img.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
using (System.Drawing.Graphics Graphic_img = System.Drawing.Graphics.FromImage(bmp_img))
{
//setting the “Graphic_img” properties
Graphic_img.SmoothingMode = SmoothingMode.AntiAlias;
Graphic_img.InterpolationMode = InterpolationMode.HighQualityBicubic;
Graphic_img.PixelOffsetMode = PixelOffsetMode.HighQuality;
Graphic_img.DrawImage(OriginalImage, new System.Drawing.Rectangle(0, 0, Width, Height), X, Y, Width, Height, System.Drawing.GraphicsUnit.Pixel);
MemoryStream MS = new MemoryStream();
bmp_img.Save(MS, OriginalImage.RawFormat);
return MS.GetBuffer();
}
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
//For image Thumbnail which crop once again to cropped image.
private void MakeThumbnail()
{
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image imagesize = System.Drawing.Image.FromFile(ResolveUrl(Server.MapPath(“images/crop/” + ViewState["imgcrop"].ToString())));
Bitmap bitmapNew = new Bitmap(imagesize);
if (imagesize.Width < imagesize.Height)
{
// Here you can set the height and width acc. to your requirement and can set Graphics “GR” properties for better quality.
Thumbnail_img = bitmapNew.GetThumbnailImage(118 * imagesize.Width / imagesize.Height, 128, myCallback, IntPtr.Zero);
System.Drawing.Graphics GR = System.Drawing.Graphics.FromImage(Thumbnail_img);
GR.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
GR.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
GR.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Threading.Thread.Sleep(500);
}
else
{
Thumbnail_img = bitmapNew.GetThumbnailImage(118 * imagesize.Height / imagesize.Width, 128, myCallback, IntPtr.Zero);
System.Drawing.Graphics GR = System.Drawing.Graphics.FromImage(Thumbnail_img);
GR.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
GR.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
GR.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
System.Threading.Thread.Sleep(500);
}
//storing the new name of the image which will display the output.
ViewState["new_img_name"] = Guid.NewGuid() + ViewState["imgcrop"].ToString().Substring(ViewState["imgcrop"].ToString().LastIndexOf(“.”));
//With Guid.NewGuid() i will rename the image after substring the “crop image name” and save it into the Profile_pics.
Thumbnail_img.Save(ResolveUrl(Server.MapPath(“Profile_pics/”)) + ViewState["new_img_name"].ToString(), System.Drawing.Imaging.ImageFormat.Jpeg);
System.Threading.Thread.Sleep(500);
lbl_msg.Text = “Successfully uploaded”;
}
//Return thumbnail callback
public bool ThumbnailCallback()
{
return true;
} }
OUPUT
Click on the below images.
download the following files…
jquery.Jcrop.min and jquery.Jcrop and jquery.Jcrop.CSs
with regards
vik







its very nice artical but i got error here sir->
Thumbnail_img.Save(ResolveUrl(Server.MapPath(“Profile_pics/”)) + ViewState["new_img_name"].ToString(), System.Drawing.Imaging.ImageFormat.Jpeg);
error GDI
Try to increase in each thread sleep amount e.g.
System.Threading.Thread.Sleep(600);
hope it will help u…
could you let me know the exact error u r facing…???
Thumbnail_img.Save(ResolveUrl(Server.MapPath(“Profile_pics/”)) + ViewState["new_img_name"].ToString(), System.Drawing.Imaging.ImageFormat.Jpeg);
in this pont runtime error coming like this sir ->
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
the crop image and original image not save into the crop and Profile_pics folders .i change the value from 500 to 600 but i got same error
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+. sir
Same here….
error occur at:
Cropped_Image.Save(Save_image_to, Cropped_Image.RawFormat);
Error: A generic error occurred in GDI+.
Ok it work after increase each thread sleep.
Btw, is it because the image need some time to upload into the directory? Therefore increasing the thread sleep and it work?
If yes, is it possible to check the existence of image before proceed?
I copied this code exactly and downloaded the 2 js files but when I try to open the page I get: ‘Microsoft JScript runtime error: object expected’
and this method is highlighted.
jQuery(function($){
// To hold the API and image size.
This happens even before the page finishes loading and before I get as far as uploading an image.
well this kind of error i never faced it but for
u i have sent the files into ur email id ortinodjs@aol.com
hope this will solve ur problem
with regards
vik
I copied this code exactly and downloaded the 2 js files but after i upload the image i am not getting the crop tool?
Now i got the Crop tool but i am not get the selected Coordinates of the image (hidden variables value)
kindly download the .css file also as i have already provide the link with js files.
I used this image cropping in my website application and i published my IIS. Now i got one issue that is “COULD NOT FIND A PART OF THE PATH. how can i close this issue.
You did amazing work.. can you put more effort on the quality of cropped image? becoz if you r dealing with cropping images the resolution is always the priority…