How to drag, position and crop image using jquery in asp.net

Here in this tutorial I am showing you how to drag, position and crop image using jquery in asp.net.

To drag the image around an html div I used jquery draggable widget.

        $(function () {
            $('#Image1').draggable();
        })

Following Javascript code grabs the coordinates of the image we need to crop.

        $(document).ready(function () {
            $('#Image1').mouseout(function () {
                document.getElementById('hdnx').value = document.getElementById('holder').offsetLeft - document.getElementById('Image1').offsetLeft;
                document.getElementById('hdny').value = document.getElementById('holder').offsetTop - document.getElementById('Image1').offsetTop;
                document.getElementById('hdnw').value =  document.getElementById('holder').offsetWidth;
                document.getElementById('hdnh').value =  document.getElementById('holder').offsetHeight;
            });
        });

And finally asp.net code to crop the image.

        Dim filename As String = ViewState("filenaam")
        Dim filepath As String = Server.MapPath("/images/" + ViewState("filenaam"))
        Dim oriimg As Image = Image.FromFile(filepath)
        Dim cropingcords As New Rectangle(Convert.ToInt32(hdnx.Value), Convert.ToInt32(hdny.Value), Convert.ToInt32(hdnw.Value), Convert.ToInt32(hdnh.Value))
        Dim cropedfilename As String, cropedfilepath As String
        Dim bitMap As New Bitmap(cropingcords.Width, cropingcords.Height, oriimg.PixelFormat)
        Dim grph As Graphics = Graphics.FromImage(bitMap)
        grph.DrawImage(oriimg, New Rectangle(0, 0, bitMap.Width, bitMap.Height), cropingcords, GraphicsUnit.Pixel)
        cropedfilename = filename
        oriimg.Dispose()
        cropedfilepath = Server.MapPath("/images/" + "crop_image.jpg")
        bitMap.Save(cropedfilepath)
        hdnx.Value = 0
        hdny.Value = 0
        hdnw.Value = 0
        hdnh.Value = 0
        Dim theCropedFileName As String = Path.Combine(Server.MapPath("~/images"), "crop_image.jpg")
        If File.Exists(theCropedFileName) Then
            Image2.ImageUrl = ("images/" + "crop_image.jpg")
        End If

You can download the complete source code here.

If you enjoyed the post, please like my blog.

Dear thoughtful people, please note that this blog is powered by Akismet : Spam Comment Filter so before posting any comment make sure that your comment is relevant to the post and carries value for other readers otherwise your time and energy directly goes to spam sac.

Comments are closed.