Crop image files in ASP.NET Core

GemBox.Imaging is a standalone .NET component that's ideal for web applications because of its fast performance and thread safety when working with multiple Image objects.

With GemBox.Imaging you can build web applications that target ASP.NET Core 2.0 and above. The following live demos show how you can create web apps that generate Word and PDF files and download them to your browser.

To use GemBox.Imaging, simply install the GemBox.Imaging package with NuGet or add the following package reference in the project file.

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="GemBox.Imaging" Version="*" />
    </ItemGroup>

</Project>

Crop image files in ASP.NET Core MVC

The following example shows how you can create an ASP.NET Core MVC application that:

  1. Imports data from a web form into an Image object.
  2. Crops the image with the given parameters.
  3. Downloads the cropped image file with a FileStreamResult.
Importing data from Razor view and cropping image file in ASP.NET Core MVC application
Screenshot of submitted web form and cropped image file
@using ImagingCoreMvc.Models;
@model CropImageModel

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GemBox.Imaging in ASP.NET Core MVC application</title>
    <link rel="icon" href="~/favicon.ico" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-controller="Home" asp-action="Index">Home</a>
            </div>
        </nav>
    </header>

    <div class="container">
        <main class="pb-3 row">
            <h1 class="display-4 p-3">Image cropper [Razor View]</h1>
            <div class="col-lg-6">
                <form asp-action="Download" enctype="multipart/form-data">
                    <div class="form-group">Image: <input asp-for="Image" class="form-control" /></div>
                    <div class="form-group">X position: <input asp-for="PosX" class="form-control" /></div>
                    <div class="form-group">Y position: <input asp-for="PosY" class="form-control" /></div>
                    <div class="form-group">Width: <input asp-for="Width" class="form-control" /></div>
                    <div class="form-group">Height: <input asp-for="Height" class="form-control" /></div>
                    <div class="form-group"><input type="submit" value="Crop" class="btn btn-primary" /></div>
                </form>
            </div>
        </main>
    </div>

    <footer class="footer border-top text-muted">
        <div class="container">&copy; GemBox Ltd. — All rights reserved.</div>
    </footer>
</body>
</html>
using GemBox.Imaging;
using ImagingCoreMvc.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace ImagingCoreMvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment environment;

        public HomeController(IWebHostEnvironment environment)
        {
            this.environment = environment;

            // If using the Professional version, put your serial key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;
        }

        public IActionResult Index()
        {
            return View(new CropImageModel());
        }

        public FileStreamResult Download(CropImageModel model)
        {
            // Load the image.
            using var imageStream = model.Image.OpenReadStream();
            using var image = Image.Load(imageStream);

            // Execute crop process.
            image.Crop(model.PosX, model.PosY, model.Width, model.Height);

            // Save image in specified file format.
            var stream = new MemoryStream();
            image.Save(stream, model.TargetFileFormat);
            stream.Position = 0;
            // Download file.
            return File(stream, model.TargetContentType, $"Output.{model.TargetFormat}");
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel() { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        private class ErrorViewModel
        {
            public ErrorViewModel()
            {
            }

            public string RequestId { get; set; }
        }
    }
}

namespace ImagingCoreMvc.Models
{
    public class CropImageModel
    {
        public IFormFile Image { get; set; }
        public int PosX { get; set; }
        public int PosY { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string TargetFormat
        {
            get
            {
                var format = Path.GetExtension(Image.FileName).ToLowerInvariant();
                return FormatMappingDictionary.ContainsKey(format) ? format : ".png";
            }
        }

        public ImageFileFormat TargetFileFormat => FormatMappingDictionary[this.TargetFormat];
        public string TargetContentType => ContentTypeMappingDictionary[this.TargetFormat];

        public static IDictionary<string, ImageFileFormat> FormatMappingDictionary => new Dictionary<string, ImageFileFormat>()
        {
            [".png"] = ImageFileFormat.Png,
            [".jpeg"] = ImageFileFormat.Jpeg,
            [".gif"] = ImageFileFormat.Gif,
            [".tiff"] = ImageFileFormat.Tiff
        };

        public static IDictionary<string, string> ContentTypeMappingDictionary => new Dictionary<string, string>()
        {
            [".png"] = "image/png",
            [".jpeg"] = "image/jpeg",
            [".gif"] = "image/gif",
            [".tiff"] = "image/tiff"
        };
    }
}

Crop image files in ASP.NET Core Razor Pages

The following example shows how you can create an ASP.NET Core Razor Pages application that:

  1. Imports data from a web form into an Image object.
  2. Crops the image with the given parameters.
  3. Downloads the cropped image file with a FileStreamResult.
Importing data from Razor page and cropping image file in ASP.NET Core MVC application
Screenshot of submitted web form and cropped image file
@page
@using ImagingCorePages.Models;
@using ImagingCorePages.Pages;
@model IndexModel

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GemBox.Imaging in ASP.NET Core MVC application</title>
    <link rel="icon" href="~/favicon.ico" />
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
    <header>
        <nav class="navbar border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-controller="Home" asp-action="Index">Home</a>
            </div>
        </nav>
    </header>

    <div class="container">
        <main class="pb-3 row">
            <h1 class="display-4 p-3">Image cropper [Razor Page]</h1>
            <div class="col-lg-6">
                <form asp-action="Download" enctype="multipart/form-data">
                    <div class="form-group">Image: <input asp-for="Model.Image" class="form-control" /></div>
                    <div class="form-group">X position: <input asp-for="Model.PosX" class="form-control" /></div>
                    <div class="form-group">Y position: <input asp-for="Model.PosY" class="form-control" /></div>
                    <div class="form-group">Width: <input asp-for="Model.Width" class="form-control" /></div>
                    <div class="form-group">Height: <input asp-for="Model.Height" class="form-control" /></div>
                    <div class="form-group"><input type="submit" value="Crop" class="btn btn-primary" /></div>
                </form>
            </div>
        </main>
    </div>

    <footer class="footer border-top text-muted">
        <div class="container">&copy; GemBox Ltd. — All rights reserved.</div>
    </footer>
</body>
</html>
using GemBox.Imaging;
using ImagingCorePages.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections.Generic;
using System.IO;

namespace ImagingCorePages.Pages
{
    public class IndexModel : PageModel
    {
        private readonly IWebHostEnvironment environment;

        [BindProperty]
        public CropImageModel Model { get; set; }

        public IndexModel(IWebHostEnvironment environment)
        {
            this.environment = environment;
            this.Model = new CropImageModel();

            // If using the Professional version, put your serial key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
            ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial;
        }

        public void OnGet() { }

        public FileStreamResult OnPost()
        {
            // Load the image.
            using var imageStream = this.Model.Image.OpenReadStream();
            using var image = Image.Load(imageStream);

            // Execute crop process.
            image.Crop(this.Model.PosX, this.Model.PosY, this.Model.Width, this.Model.Height);

            // Save image in specified file format.
            var stream = new MemoryStream();
            image.Save(stream, this.Model.TargetFileFormat);
            stream.Position = 0;
            // Download file.
            return File(stream, this.Model.TargetContentType, $"OutputFromPage.{this.Model.TargetFormat}");
        }
    }
}

namespace ImagingCorePages.Models
{
    public class CropImageModel
    {
        public IFormFile Image { get; set; }
        public int PosX { get; set; }
        public int PosY { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public string TargetFormat
        {
            get
            {
                var format = Path.GetExtension(Image.FileName).ToLowerInvariant();
                return FormatMappingDictionary.ContainsKey(format) ? format : ".png";
            }
        }
        public ImageFileFormat TargetFileFormat => FormatMappingDictionary[this.TargetFormat];
        public string TargetContentType => ContentTypeMappingDictionary[this.TargetFormat];

        public static IDictionary<string, ImageFileFormat> FormatMappingDictionary => new Dictionary<string, ImageFileFormat>()
        {
            [".png"] = ImageFileFormat.Png,
            [".jpeg"] = ImageFileFormat.Jpeg,
            [".gif"] = ImageFileFormat.Gif,
            [".tiff"] = ImageFileFormat.Tiff
        };

        public static IDictionary<string, string> ContentTypeMappingDictionary => new Dictionary<string, string>()
        {
            [".png"] = "image/png",
            [".jpeg"] = "image/jpeg",
            [".gif"] = "image/gif",
            [".tiff"] = "image/tiff"
        };
    }
}

Host and deploy ASP.NET Core

GemBox.Imaging follows a licensing model per individual developer, which includes royalty-free deployment. You are allowed to build an unlimited number of applications and deploy or distribute them across numerous services, servers, or end-user machines without any additional cost. For more information, read our End User License Agreement (EULA).

See also


Next steps

GemBox.Imaging is a .NET component that provides an easy way to load, edit, save images. GemBox.Imaging also supports file format conversions and image transformations (resize, crop, rotate and flip).

Download Buy