Header add

 In this article we will discuss How to Crop Image using jquery.

Here we will explain how to crop and upload Image with thumbnail preview using jQuery and HTML5 Canvas in ASP.Net Core MVC.

Before start this article, please visit our previous article Import (Insert) Excel file data into Database ASP.Net Core MVC

The image will be cropped using the Jcrop jQuery plugin, and the thumbnail preview is displayed using HTML5 Canvas and finally the Cropped Image is uploaded and saved in a folder on server using ASP.Net Core MVC.

View

The View consists of a FileUpload element, an Image element, a Button, a Submit Button, an HTML5 Canvas elements and some hidden field elements.

Inside the jQuery document ready event handler, a change event handler is assigned to a FileUpload control and a click event handler is assigned to the HTML Button.

When a file is selected in the HTML FileUpload control, it is read using HTML5 FileReader API and then the image is displayed in the Image element and finally the Jcrop jQuery plugin is applied to the Image element.

The Jcrop plugin makes a call to SetCoordinates function on its onChange and onSelect event handlers, which allow us to save the coordinates and dimensions i.e. height and width of the cropped image to the hidden fields.

When the Crop Button is clicked, it first creates an instance of the HTML5 Canvas and then loads the Image into an Image object with an OnLoad event handler.

Inside the OnLoad event handler, the original image is redrawn on the canvas using the saved coordinates and dimensions i.e. height and width of the cropped image.

Finally the base64 string of the cropped image is fetched from the Canvas using the toDataURL method and is saved in the imgCropped hidden field.


Controller

The Controller consists of two Action methods.
  • Action method for handling GET operation
  • Inside this Action method, simply the View is returned.
Action method for handling POST operation for uploading the Cropped Image

This Action method gets called when the Upload Button is clicked. The cropped image is read as BASE64 string from the imgCropped hidden field using its Name from the Request.Form collection and then it is converted to a Byte Array. Then the Byte Array is saved into the Images folder inside the wwwroot folder using FileStream class.


Output

Now you can see that we can crop the image like below,


</> Find the Source Code in Github

  Summary

Post a Comment

Previous Post Next Post