Tuesday, 11 October 2011

Image Cropping.

Hi,
 Well if you are going to crop or re-size your image then it is the best way for cropping any type of image.
I have implemented this code in asp.net. For cropping the image you should have to use jQuery and file uploader.


For cropping image you need to have some hidden fields for getting coordinates or position of cropping window.
This is the HTML code.


<asp:Panel ID="pnlUpload" runat="server">
            <div class="lblcol">
                <asp:Label ID="Label4" runat="server" Text="ImageUpload"></asp:Label>
            </div>
            <div class="ctrlcol" style=" width:auto">
                <asp:FileUpload ID="Upload" runat="server" />
                <br />
            </div>
            <div class="lblcol" style=" margin-left:10px">
                <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload" OnClientClick="return uploadvalidate();" />
                <asp:Label ID="lblError" runat="server" Visible="false" /></div>
        </asp:Panel>
    </div>
    <asp:Panel ID="pnlCrop" runat="server" Visible="false">
        <div class="formcontainer" style=" margin-bottom:8px">
            <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" />
        </div>
    </asp:Panel>
    <asp:Panel ID="pnlCropped" runat="server" Visible="false">
        <div class="formcontainer" style=" margin-bottom:8px">
            <asp:Image ID="imgCropped" runat="server" />
        </div>
    </asp:Panel>


And you have to use some jQueries for enable the cropping window.

<link href="css/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
    <link href="css/demos.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.pack.js"></script>

    <script type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>

    <script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery('#ctl00_MainContent_imgCrop').Jcrop({
      onChange:   storeCoords,
        onSelect:   storeCoords,
        onRelease:  clearCoords,
        bgColor:     'black',
        bgOpacity:   .4,
        setSelect: [ 208, 110, 50, 50],
       
        minSize:[208, 110],
        maxSize:[208, 110]

    });
  });

  function storeCoords(c) {
  var pic = jQuery('#ctl00_MainContent_imgCrop');
   var width = jQuery('#ctl00_MainContent_X');
   var height = jQuery('#ctl00_MainContent_Y');
   pic.removeAttr(width);
   pic.removeAttr(height);
   if(pic.width() > 208 && pic.height() > 110 )
   {
    jQuery('#ctl00_MainContent_X').val(c.x);
    jQuery('#ctl00_MainContent_Y').val(c.y);
    jQuery('#ctl00_MainContent_W').val(c.w);
    jQuery('#ctl00_MainContent_H').val(c.h);
    }
    else
    {
    jQuery('#ctl00_MainContent_X').val(c.x);
    jQuery('#ctl00_MainContent_Y').val(c.y);
    jQuery('#ctl00_MainContent_W').width(c.w);
    jQuery('#ctl00_MainContent_H').height(c.h);
    }
  };
 
  function clearCoords()
    {
      $('#coords input').val('');
      $('#h').css({color:'red'});
      window.setTimeout(function(){
        $('#h').css({color:'inherit'});
      },500);
    };

    </script>

When you upload an image and press on button it will show that image. Which is having cropping window. In my case the size of cropping window is fixed but if you want to resize the window than you can change it from jQuery.
After uploading the image it look likes.


Which is having crop button also.You can move this cropping window to any where. It will then get the position of X and Y coordinates and height, width also.  After fix the cropping part when you click on the crop button it will catch the coordinates and file path with name as well. The crop function will set all graphic mode regarding its smoothness, quality or Pixel offset mode.

You must require some reference file for crop.

using SD = System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;

And the function code when you click on the crop button.

protected void btnCrop_Click(object sender, EventArgs e)
    {
        hndCrop.Value = "1";
        string ImageName = ViewState["NewFileName"].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 = Croppath + "crop_" + ImageName;
                ViewState["CroppedImage"] =  "crop_" + ImageName;
                strFileNameSmall = "crop_" + ImageName;
                CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
                pnlCrop.Visible = false;
                pnlCropped.Visible = true;
                imgCropped.ImageUrl = "UploadedImages/SmallImg/crop_" + ImageName;
               
                pnlUpload.Visible = true;
            }
        }
    }

    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, PixelFormat.Format24bppRgb))
                {
                    bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                    using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode = SmoothingMode.HighQuality; // SmoothingMode.AntiAlias;
                        Graphic.InterpolationMode = InterpolationMode.High;    //.HighQualityBicubic;
                        Graphic.CompositingQuality = CompositingQuality.HighQuality;
                        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);
        }
    }

The last cropped image will appear after clicking on the crop button.


This the cropped image.
So, I think this code is very easy for you to use. Now upload image and crop it in your own way. And have fun with the code.



Tuesday, 26 April 2011

Add new row at runtime in Grid View.

Hello,
     If you want to add new row in grid view at run time using ASP.NET(C# ) then firstly you need to have labels, textbox in your grid view.

Here is the image of that grid view on which we are going to work...

The Source code for creating grid view is like....

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
            AllowSorting="True" AutoGenerateColumns="False" BackColor="White"
            BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
            onpageindexchanging="GridView1_PageIndexChanging"
            onrowcancelingedit="GridView1_RowCancelingEdit"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
            onrowupdating="GridView1_RowUpdating" onsorting="GridView1_Sorting"
            PageSize="5" ShowFooter="True" ForeColor="Black" GridLines="Vertical">
            <AlternatingRowStyle BackColor="#CCCCCC" />
            <Columns>
                <asp:TemplateField HeaderText="ID" SortExpression="ID">
                    <EditItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="NAME" SortExpression="NAME">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SALARY" SortExpression="SALARY">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("salary") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("salary") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowSelectButton="True" />
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
            <FooterStyle BackColor="#CCCCCC" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#808080" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#383838" />
        </asp:GridView>



Now, When you fill the text box for name and salary....and click on the insert button like......


The code to insert the value in grid view..


protected void Insert_Click(object sender, EventArgs e)
    {
        con.Open();
       
        TextBox empNAME = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
        TextBox empSALARY = (TextBox)GridView1.FooterRow.FindControl("TextBox5");
      
       
        String insertquery="insert into emp values('"+empNAME.Text+"','"+empSALARY.Text+"')";
        SqlCommand cmd = new SqlCommand(insertquery, con);
        Response.Write("1 Row has been inserted. ");
        cmd.ExecuteNonQuery();
        con.Close();
        GridView1.EditIndex = -1;
        BindData();

    }




The final image after inserting the values in grid view is....












Monday, 18 April 2011

CLR(Common Language Runtime)

CLR(Common Language Runtime) : The CLR is an application virtual machine.The CLR is described as the "execution engine" of .NET. It's this CLR that manages the execution of programs. The CLR is the engine that compiles the source code in to an intermediate language. This intermediate language is called the Microsoft Intermediate Language(MSIL) also known as CIL(common Intermidiate Language).

Commom Language Runtime

Friday, 15 April 2011

What is .NET Framework

The .NET Framework is a Software Framework that run on the Microsoft Windows.

The .NET Framework includes a large library. It supports several programming languages which allows language interoperability. The .NET library is available to all the programming languages that .NET supports. The Base class library and the CLR(Common Language Runtime) together constitute the .NET Framework.

Base Class Library : The .NET framework's Base Class Library provides user interface, data access,database connectivity, cryptography, web application development, numeric algorithms, and network communications. The class library is used by programmers, who combine it with their own code to produce applications.

.NET Framework
During the execution of the program this MSIL is converted to the native code or the machine code. This conversion is possible through the Just-In-Time compiler. During compilation the end result is a Portable Executable file (PE). 


ADO.NET : ADO.NET is the new database technology of the .NET platform, and it builds on Microsoft ActiveX Data Objects (ADO).

ADO.NET is an integral part of the .NET Compact Framework, providing access to relational data, XML documents, and application data. ADO.NET supports a variety of development needs. You can create database-client applications and middle-tier business objects used by applications, tools, languages or Internet browsers.
ADO.NET

I LOVE MY LIFE.

Hi, This is Nishant Sukhwal.