Search code examples
c#jqueryasp.netimagecrop

Crop an image in asp.net using c#


I am working on asp.net using c#. I have to adjust an image by taking a portion of that image. I want to crop a portion of image from middle like in the below image.

enter image description here

can anyone help me please.


Solution

  • I have done this by getting co-ordinates of the image's portion by Jquery.

    jQuery(function($) {
            $('#target').Jcrop({
                onChange: showCoords,
                onSelect: showCoords,
                onRelease: clearCoords
            });
        });
        function showCoords(c) {
            $('#xaxis').val(c.x);
            $('#yaxis').val(c.y);
            $('#x2').val(c.x2);
            $('#y2').val(c.y2);
            $('#xwidth').val(c.w);
            $('#div_width').val(c.w);
            $('#yheight').val(c.h);
            $('#div_height').val(c.h);
        };
        function clearCoords() {
            $('#coords input').val('0');
            $('#yheight').css({ color: 'red' });
            window.setTimeout(function() {
                $('#yheight').css({ color: 'inherit' });
            }, 500);
        };
    

    Then I used these co-ordinates to crop image in C# like

    String savedFileName = uploadProfileImage(profileImageName, new System.Drawing.Rectangle(Int32.Parse(xaxis), Int32.Parse(yaxis), Int32.Parse(xwidth), Int32.Parse(yheight)));
    
    public String uploadProfileImage(string profileImageName, System.Drawing.Rectangle rectangle)
        {
            try
            {
                String retFileName = "";
                if (profileImageName != null || profileImageName != "")
                {
                    GenerateCroppedThumbNail(profileImageName, rectangle);
                }
                return retFileName;
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
    

    That works fine