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.