Search This Blog

Tuesday 27 November 2012

How to crop image using ASP.Net/C# OR Cropping image in C# before upload


Crop images before upload to the server in C#/ASP.Net
In our previous post we demonstrate how we can re size image using C# or Create thumbnail image using ASP.Net. Here we are demonstrating how we can crop images using ASP.Net application using Jquery and C#. In some applications we need to upload images and we need only some portion of the images to get clear picture on the photo. In this case we need to give an option to users to crop image before they are uploading the image.
Include Jquery file/CSS files to the application. 
First of all we need to include following jquery/CSS files to the application.
1.       jquery.min.js
2.       jquery.Jcrop.js
3.       jquery.Jcrop.css
Simple steps to crop image using ASP.Net,C#,Jquery
In this application we are having a browse option for selecting an image. Once we selected a image it will display int the screen.
Crop image using ASP.net C#
Select an image to crop using ASP.Net C# Jquery
In the next step we will have the option to select an area to crop the image. Once we selected an area we can click crop button on the screen.
Crop image using ASP.Net C#
Select image area to crop
Then the selected area will be cropped and displayed in the screen.
Crop image using ASP.Net C#
Cropped area of the image
ASPX Page for crop images using Jquery 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CropImage.aspx.cs" 
Inherits="ExperimentLab.CropImage" %>
<!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 Image</title>
 <link href="Styles/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 type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>
 <script type="text/javascript">
 jQuery(document).ready(function () {
 jQuery('#imgCrop').Jcrop({
 onSelect: storeCoords
 });
 });
function storeCoords(c) {
 jQuery('#X').val(c.x);
 jQuery('#Y').val(c.y);
 jQuery('#W').val(c.w);
 jQuery('#H').val(c.h);
 };
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Panel ID="pnlUpload" runat="server">
 <asp:FileUpload ID="Upload" runat="server" />
 <br />
 <asp:Button ID="btnUpload" runat="server" 
 OnClick="btnUpload_Click" Text="Upload" />
 <asp:Label ID="lblError" runat="server" Visible="false" />
 </asp:Panel>
 <asp:Panel ID="pnlCrop" runat="server" Visible="false">
 <asp:Image ID="imgCrop" 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="btnCrop" runat="server" Text="Crop" 
 OnClick="btnCrop_Click" />
 </asp:Panel>
 <asp:Panel ID="pnlCropped" runat="server" Visible="false">
 <asp:Image ID="imgCropped" runat="server" />
 </asp:Panel>
 </div>
 </form>
</body>
</html>
Code Behind of the ASPX page for Crop image using ASP.Net/C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Drawing2D;
namespace ExperimentLab
{
public partial class CropImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
protected void btnUpload_Click(object sender, EventArgs e)
{
Boolean FileOK = false;
Boolean FileSaved = false; 
if (Upload.HasFile)
{
Session["WorkingImage"] = Upload.FileName;
String FileExtension =
Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
 FileOK = true;
}
}
}
if (FileOK)
{
try
{
Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
FileSaved = true;
}
catch (Exception ex)
{
lblError.Text = "File could not be uploaded." + ex.Message.ToString();
lblError.Visible = true;
FileSaved = false;
}
}
else
{
lblError.Text = "Cannot accept files of this type.";
lblError.Visible = true;
}
if (FileSaved)
{
pnlUpload.Visible = false;
pnlCrop.Visible = true;
imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
}
}
protected void btnCrop_Click(object sender, EventArgs e)
{
string ImageName = Session["WorkingImage"].ToString();
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
byte[] CropImage = Crop(path + ImageName, w, h, x, y);
using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
{
ms.Write(CropImage, 0, CropImage.Length);
using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
{
string SaveTo = path + "crop" + ImageName;
CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
pnlCrop.Visible = false;
pnlCropped.Visible = true;
imgCropped.ImageUrl = "images/crop" + ImageName;
}
}
}
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
try
{
using (SD.Image OriginalImage = SD.Image.FromFile(Img))
{
using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
{
 bmp.SetResolution(OriginalImage.HorizontalResolution, 
 OriginalImage.VerticalResolution);
 using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
 {
 Graphic.SmoothingMode = SmoothingMode.AntiAlias;
 Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
 Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
 Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height),
 X, Y, Width, Height, SD.GraphicsUnit.Pixel);
 MemoryStream ms = new MemoryStream();
 bmp.Save(ms, OriginalImage.RawFormat);
 return ms.GetBuffer();
 }
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
}
}

Tuesday 20 November 2012

Disable copy paste on textbox in the ASP.Net/C# using javascript/Jquery


Very simple method to disable copy paste in the textbox without any extra script
To achieve some requirements like disable copy paste functionalities in the textbox in aspx page, commonly we need to write some additional javascript functionalities in the aspx page. We can achieve this features using very simple methods.
First Method to disable Ctrl Key and right click on textbox
This method is very simple method and here we don’t need to include any javascript methods or files. We are having oncopy and onpaste event for the textboxes and can call return false for this both event.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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>Sample to Disable Copy, Cut and Paste Options in textbox</title>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>First Method To disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox2" runat="server" oncopy="return false" oncut="return false"
 onpaste="return false"></asp:TextBox>
 </div>
 </form>
</body>
</html>
Second method to prevent copy paste feature in the aspx texbox
In this option, we are calling a javascript function on any key press. This function checks whether user press ctrl key or right click using e.keyCode and e.button variable. If the user press ctrl key or right click, from the javascript function call return false
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!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>Sample to Disable Copy, Cut and Paste Options in textbox</title>
 <script language="javascript" type="text/javascript">
//Function to disable Cntrl key/right click
function DisableControlKey(e) {
// Message to display
var message = "Cntrl key/ Right Click Option disabled";
// Condition to check mouse right click / Ctrl key press
if (e.keyCode == 17 || e.button == 2) {
alert(message);
return false;
}
}
</script>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>Second Method to Disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox3" runat="server" onKeyDown="return DisableControlKey(event)"
 onMouseDown="return DisableControlKey(event)"></asp:TextBox>
 </div>
 </form>
</body>
</html>

Tuesday 13 November 2012

Disable right click on a web page in asp.net/C# using Jquery/Javascript


How to disable right click functionality from the asp.net web page
In some of the web page has the requirement to protect source code from the users. Users can right click the page and take the source code. In order protect right click functionality on the web page we can implement javascript functionality to prevent user’s right click on the web page. So user not able to access features available on the right click menus.
By implementing javascript method we can identify the right click event from the user by checking the button code and prevent if the user clicks right click. Below mentioned web page prevented to click right click by the user. When the user trying to right click it will return warning message to user and return the action.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisableRightClick.aspx.cs"
 Inherits="ExperimentLab.DisableRightClick" %>
<!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>Sample to Disable Right Click of Page</title>
 <script language="JavaScript" type="text/javascript">
 //Message to display whenever right click on website
 var message = "Sorry, Right Click have been disabled.";
 function click(e) {
 if (document.all) {
 if (event.button == 2 || event.button == 3) {
 alert(message);
 return false;
 }
 }
else {
 if (e.button == 2 || e.button == 3) {
 e.preventDefault();
 e.stopPropagation();
 alert(message);
 return false;
 }
 }
 }
if (document.all) {
 document.onmousedown = click;
 }
else {
 document.onclick = click;
 }
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 In this page right click not allowed.
 </div>
 </form>
</body>
</html>

Tuesday 6 November 2012

How to calculate difference between two dates in javascript/jquery


Simple steps to calculate difference between two date fields using JavaScript/JQuery 
In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks
Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 
Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.
function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}
How to calculate the date difference from client side using javascript?
Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.
Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.
function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}
In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}
ASPX page having two date fields as follows :
<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>