Source: Intelliwins BlogAsp.net image uploader has a very limited scope in uploading image file. We have previously tried our hand in giving the file upload control an option to select the color from the uploaded image. This time we tried to give the option to crop a uploaded image and also resize the image while uploading. We will user Jquery and Jquery jcrop with asp.net file upload control. I have also used Master page , Some times master is the culprit in using asp.net controls with jquery. Masterpage.master <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!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 runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
<style>
#load
{
position: absolute;
left: 35%;
top: 38%;
position:fixed;
height: 200px;
width: 300px;
z-index: 1000;
margin:-25px 0 0 -25px;
display:none;
background-color: #FFF;
padding: 30px 40px 34px;
-moz-box-shadow: 0 0 10px rgba(0,0,0,.4);
-webkit-box-shadow: 0 0 10px rgba(0,0,0,.4);
-box-shadow: 0 0 10px rgba(0,0,0,.4);
}
.bg {
position: fixed;
height: 100%;
width: 100%;
background: #000;
background: rgba(0,0,0,.8);
z-index: 100;
display: none;
top: 0;
left: 0;
}
.fle
{
display:none !important;
}
</style>
<link href="CSS/Style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="load">
<div style="width:100%;text-align:center; padding-top:20px;"><h5>Loading....</h5></div>
<div align="center" style="padding-top:30px;"> <img src="images/ajax-loader.gif" /></div>
</div>
<div class="bg"></div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html> Default.aspx<%@ Page Title="" Language="C#" ClientIDMode="Static" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<link href="CSS/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="CSS/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.Jcrop.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//Intialize JCROP
$('#imgCrop').Jcrop({
onSelect: storeCoords
}, function () {
jcrop_api = this;
//Setting Aspect Ratio
jcrop_api.setOptions({ aspectRatio: 2 / 1 });
});
//Loading Box
$(document).keyup(function (event) {
if (event.which === 27) {
$('#load').hide();
$(".bg").hide();
}
});
function xy() {
$("#load").fadeIn("slow");
$(".bg").show();
setTimeout(function () {
$('#load').fadeOut("slow");
$(".bg").hide();
}, 10000);
}
$('.upl').click(function () {
xy();
});
$(".fle").on('change', function () {
$("#btn_up").click();
});
});
function storeCoords(c) {
//Co ordinates from JCROP
$('#X').val(c.x);
$('#Y').val(c.y);
$('#W').val(c.w);
$('#H').val(c.h);
};
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="container">
<div class="row">
<div class="col-md-10 frm">
<h3>Options</h3>
<asp:Panel ID="pnlupl" runat="server" Visible="true" CssClass="form-inline">
<asp:FileUpload ID="Upload" runat="server" CssClass="fle"/>
<asp:Button ID="Button1" runat="server" Text="Browse" CssClass="btn btn-warning" />
<asp:Button ID="btn_up" runat="server" Text="Upload" class="upl" onclick="btn_up_Click" CssClass="btn btn-success" style="display:none;" />
<asp:Button ID="btnCrop" runat="server" Text="Crop" class="upl" OnClick="btnCrop_Click" CssClass="btn btn-danger" />
<asp:Label ID="lblError" runat="server" Visible="false" />
</asp:Panel>
</div>
</div>
<div class="row">
<div class="col-md-10 frm">
<h4>Image <span class="text-danger">(Crop Aspect Ratio 2:1)</span> </h4>
<asp:Panel ID="pnlCrop" runat="server" Visible="false">
<asp:Image ID="imgCrop" runat="server" CssClass="img-responsive" />
<asp:Image ID="imgCropped" 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:Panel>
</div>
</div>
</div>
</asp:Content>Default.aspx.csusing 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.Imaging;
using System.Drawing.Drawing2D;
public partial class _Default : System.Web.UI.Page
{
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
String tpath = HttpContext.Current.Request.PhysicalApplicationPath + "thumb_img\\";
protected void Page_Load(object sender, EventArgs e)
{
//Set button to open upload box
Button1.Attributes.Add("onclick", "jQuery('#" + Upload.ClientID + "').click();return false;"); //It is mck the opening of file upload control
}
protected void btn_up_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(MapPath("images/") + Session["WorkingImage"]); //Save Original Image
System.Drawing.Image img1 = System.Drawing.Image.FromFile(MapPath("images/") + Session["WorkingImage"]);
int xx = img1.Width;
int yy = img1.Height;
double y = Convert.ToDouble(yy);
int wid = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["width"]);
double hi = (y / xx) * wid;
int h = (int)hi;
System.Drawing.Image bmp1 = ResizeImage(img1, wid, h);
var bmp2 = new SD.Bitmap(bmp1);
bmp2.Save(MapPath("images/") + "resized" + Session["WorkingImage"]);//Save Resized Image
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)
{
pnlCrop.Visible = true;
imgCrop.ImageUrl = "images/resized" + Session["WorkingImage"].ToString();
imgCrop.Visible = true;
imgCropped.Visible = false;
}
}
protected void btnCrop_Click(object sender, EventArgs e)
{
try
{
string ImageName = "resized" + 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(MapPath("images/") + 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 = MapPath("images/") + "crop" + ImageName;
CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
imgCrop.Visible = false;
imgCropped.Visible = true;
imgCropped.ImageUrl = "images/crop" + ImageName;
}
}
}
catch (Exception)
{
}
}
static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{//Crop image according to selected cordinate
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
Read full article »
Followers on Owler
1