This time I want to show how easy it is to use CoreCompat.System.Drawing image processing package to crop the images in ASP.NET Core. We will create simple web application with the only one controller and action. This action will download the source image, crop it using the given parameters, and write resulting image to the response stream.
Let’s start from creating an empty ASP.NET Core project. Add all references that are required for any MVC application. Also, add references to these packages:
While ASP.NET Core doesn’t have any built-in classes to work with the images, we have to use the third-party ones. You can take a look at other options you have here. I have chosen CoreCompat.System.Drawing in my Platformus project because it has the same public interface like well-known System.Drawing, but using the ImageSharp library might be a good idea too.
Ok. Now create the ImageController controller with the Index action. This action will do all the work: downloading an image, cropping it, and writing the result to the response stream (everything will be processed in memory, without writing to disk). It should be asynchronous, because image downloading may take time, so controller can process other requests during the downloading process. This is how the action may look like:
As you can see, first of all we have to load the image from the given URL. It is done by the LoadImageFromUrl method:
As I said before, all the network-related actions are asynchronous here.
Now let’s take a look at the cropping method itself:
The method is extremely simple. We create the destination image with the size specified by the user. Then we create the Graphics object from that image. And finally we write the specified part of the source image into the destination one using the Graphics object.
Now we only have to save the cropped image into the memory stream and then copy that stream into the request output stream using the File extension method of the controller.
Run the application. You will have the 404 error (because we don’t have a default controller). Navigate to /image and pass all the required parameters like this:
This is the original photo of my cat as a sample:
And this is the cropped one:
As usual, I have created the demo project for this post. Feel free to ask if you have any questions!