Intelliwins Blog

Anything you wanna know about? Image Upload With Crop

by Admin 12. February 2015 22:16 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 file upload control.  I have also used Master page , Some times master is the culprit in using 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" ""> <html xmlns=""> <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.cs 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.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; 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); } } public static SD.Image ResizeImage(SD.Image image,int height,int width) { int newWidth; int newHeight; newWidth = height; newHeight = width; SD.Image newImage = new SD.Bitmap(newWidth, newHeight); using (var graphicsHandle = SD.Graphics.FromImage(newImage)) { graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic; graphicsHandle.SmoothingMode = SmoothingMode.HighQuality; graphicsHandle.PixelOffsetMode = PixelOffsetMode.HighQuality; graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight); } return newImage; } } Download Source

Tags: , , , , , | Jquery | Web design

Extending Image Uploader with Preview and Color Selector in

by Admin 28. April 2014 13:12
Even if default file upload control is a very powerful tool but it comes with some limitations. In this tutorial we will discuss in depth about it and way to overcome it. Limitations No Support fro Customized Button or Use of CSS Classes: Even if is a very powerful control we can't customize it with CSS classes like we can't change the text in the browse button or can't hide the textbox or apply css class to button.  No Support for image preview:  we can't preview image before uploading No validation fro file type or size No Color selector To overcome this we have extended the functionality of this control using Javascript and Jquery. Here you can customize the  button for upload, preview image, validation for image file with size. GUID support for file name and Color selection from uploaded image and stored the selected color and image to database. You can check the demo below and download the full source code   DEMO        DOWNLOAD 

Tags: , , | Jquery | Tips and tricks

Alert Box for Bootstrap 3.0

by Admin 26. November 2013 16:26
Twitter Bootstrap Comes With a Bunch of Controls for Rapid Application Development. They Enhanced and Redesigned it with the release of Version 3.0 by adapting Flat design philosophy . It has a lot of predefined controls and CSS Class which makes App design Hell lot of easier . Now this simple plugin Bootbox JS makes it Even more easier for development with some simple alert box. We use alert box or you can say message box quite often during development. When password is incorrect or when we delete a data we have a requirement for confirmation box. This tiny Jquery Library is the single stop solution for all the requirement.   Dependencies It depends on the Twitter Bootstrap 3.X and Jquery. Not that difficult i guess. Usages Once you included the dependence file the coding is quite simple. <!DOCTYPE html><html><head><meta charset="utf-8"><title>My page</title> <!-- CSS dependencies --><link rel="stylesheet" type="text/css" href="bootstrap.min.css"></head><body> <p>Content here. <a class="alert" href=#>Alert!</a></p> <!-- JS dependencies --><script src=""></script><script src="bootstrap.min.js"></script> <!-- bootbox code --><script src="bootbox.min.js"></script><script>$(document).on("click", ".alert", function(e) {bootbox.alert("Hello world!", function() {console.log("Alert Callback");});});</script></body></html> Well That It !! If you a little bit familiar with using any other Jquery library you can start working straight forward. Now some Advanced Stuffs Need a Confirmation Box The Here we are bootbox.confirm("Are you sure?", function(result) {"Confirm result: "+result);}); As Simple as that !!!   Okay Need a Customized Alert Box with Multiple Button.   bootbox.dialog({message: "I am a custom dialog",title: "Custom title",buttons: {success: {label: "Success!",className: "btn-success",callback: function() {"great success");}},danger: {label: "Danger!",className: "btn-danger",callback: function() {"uh oh, look out!");}},main: {label: "Click ME!",className: "btn-primary",callback: function() {"Primary button");}}}});   Isn't That simple .   Download Full version JS Minified Version JS

Tags: ,

CSS | Freebies | Jquery | Tips and tricks

Textbox Swapper with Jquery and CSS3

by Admin 24. September 2013 13:48
This a sample code snippet we have written during development of one of our application at intelliwins , This is a textbox swapper using jquery and CSS3 Sample Codes          $(document).ready(function () {                $(".switchFields").click(function (e) {                    swap(e, '#Text1', '#Text2');                });            });   Here .switchField is the class of the anchor which need to be clicked for the textbox swapping. Text1 and Text2 are the textbox which are swapped. Also you need to inclde the Stylesheet file and the JS file which is included in the link below with the demo application.  One more thing you need to enter some values into textbox before swapping. You could download the sample code in following link Download    

Tags: , ,

Jquery | CSS | Tips and tricks

Brit Colony, Bhubaneswar,India +91 94384 80191 info@

About Us

Intelliwins mission is to alter the dynamics of the software industry by providing trusted, supportive and quality software development servies to clients that view our partnership as a strategic driver for their success.


Enter your email to join our mailing list