Umbraco CMS
CloudHeartcoreDXPMarketplace
10.latest (LTS)
10.latest (LTS)
  • Umbraco CMS Documentation
  • Legacy Documentation
    • Umbraco 11 Documentation
    • Umbraco 8 Documentation
    • Umbraco 7 Documentation
  • Release Notes
  • Contribute
  • Sustainability Best Practices
  • Fundamentals
    • Get to know Umbraco
    • Setup
      • Requirements
      • Installation
        • Install using .NET CLI
        • Install using Visual Studio
        • Local IIS With Umbraco
        • Install Umbraco With Visual Studio Code
        • Installing Nightly Builds
        • Running Umbraco On Linux/macOS
        • Unattended Installs
      • Upgrade your project
        • Version Specific Upgrades
          • Upgrade from Umbraco 8 to Umbraco 10
          • Migrate content to Umbraco 8
          • Minor upgrades for Umbraco 8
          • Upgrade to Umbraco 7
          • Minor upgrades for Umbraco 7
      • Server setup
        • Running Umbraco On Azure Web Apps
        • Hosting Umbraco in IIS
        • File And Folder Permissions
        • Runtime Modes
        • Running Umbraco in Docker
        • Umbraco in Load Balanced Environments
          • Load Balancing Azure Web Apps
          • Standalone File System
          • Advanced Techniques With Flexible Load Balancing
          • Logging With Load Balancing
    • Backoffice
      • Sections
      • Property Editors
        • Built-in Property Editors
          • Checkbox List
          • Color Picker
          • Content Picker
          • DateTime
          • Date
          • Decimal
          • Email Address
          • Eye Dropper Color Picker
          • File Upload
          • Image Cropper
          • Label
          • List View
          • Markdown Editor
          • Media Picker
          • Media Picker (Legacy)
          • Member Group Picker
          • Member Picker
          • Multi Url Picker
          • Multinode Treepicker
          • Repeatable Textstrings
          • Nested Content (Legacy)
          • Numeric
          • Radiobutton List
          • Slider
          • Tags
          • Textarea
          • Textbox
          • Toggle
          • User Picker
          • Block Editors
            • Block Grid
            • Block List
            • Build a Custom View for a Block
            • Configuring Block Editor Label Properties
          • Dropdown
          • Grid Layout (Legacy)
            • What Are Grid Layouts?
            • Configuring The Grid Layout
            • Settings And Styling
            • Grid Editors
            • Build Your Own Editor
            • Rendering Grid In a Template
            • Grid Layout Best Practices
            • Add Values Programmatically
          • Rich Text Editor
            • Rich Text Editor Configuration
            • Rich Text Editor Styles
      • Login
      • Content Templates
      • Infinite Editing
      • Log Viewer
      • Language Variants
      • Settings Dashboards
    • Data
      • Defining Content
        • Default Document Types
      • Creating Media
        • Default Data/Media Types
      • Members
      • Data Types
        • Default Data Types
      • Scheduled Publishing
      • Using Tabs
      • Users
      • Relations
      • Dictionary Items
      • Content Version Cleanup
    • Design
      • Templates
        • Basic Razor Syntax
        • Named Sections
        • Razor Cheatsheet
      • Rendering Content
      • Rendering Media
      • Partial Views
      • Partial View Macro Files
      • Stylesheets And JavaScript
    • Code
      • Service APIs
      • Subscribing To Notifications
      • Creating Forms
      • Debugging
        • Logging
      • Source Control
  • Implementation
    • Learn how Umbraco works
    • Routing
      • Controller & Action Selection
      • Execute Request
      • Request Pipeline
    • Custom Routing
      • Adding a hub with SignalR and Umbraco
    • Controllers
    • Data Persistence (CRUD)
    • Composing
    • Integration Testing
    • Nullable Reference Types
    • Services and Helpers
      • Circular Dependencies
    • Unit Testing
  • Extending
    • Customize the editing experience
    • Dashboards
    • Sections & Trees
      • Sections
      • Trees
        • Tree Actions
      • Searchable Trees (ISearchableTree)
    • Property Editors
      • Package Manifest
      • Property Value Converters
      • Property Actions
      • Tracking References
      • Declaring your property editor
      • Content Picker Value Converter Example
    • Macro Parameter Editors
    • Health Check
      • Health Check Guides
        • Click-Jacking Protection
        • Content/MIME Sniffing Protection
        • Cross-site scripting Protection (X-XSS-Protection header)
        • Debug Compilation Mode
        • Excessive Headers
        • Fixed Application Url
        • Folder & File Permissions
        • HTTPS Configuration
        • Macro Errors
        • Notification Email Settings
        • SMTP
        • Strict-Transport-Security Header
    • Language Files & Localization
    • Backoffice Search
    • Backoffice Tours
    • Backoffice UI API Documentation
    • Content Apps
    • Creating a Custom Database Table
    • Embedded Media Providers
    • Custom File Systems (IFileSystem)
      • Using Azure Blob Storage for Media and ImageSharp Cache
    • Configuring Azure Key Vault
    • Packages
      • Package Types
      • Creating a Package
      • Language file for packages
      • Listing a Package on the Umbraco Marketplace
      • Good practice and defaults
      • Packages on Umbraco Cloud
      • Installing and Uninstalling Packages
      • Maintaining packages
      • Create accessible Umbraco packages
      • Example Package Repository
    • UI Library
  • Reference
    • Dive into the code
    • Configuration
      • Basic Authentication Settings
      • Connection strings settings
      • Content Dashboard Settings
      • Content Settings
      • Data Types Settings
      • Debug settings
      • Examine settings
      • Exception filter settings
      • FileSystemProviders Configuration
      • Global Settings
      • Health checks
      • Hosting settings
      • Imaging settings
      • Indexing settings
      • Install Default Data Settings
      • Keep alive settings
      • Logging settings
      • Maximum Upload Size Settings
      • Models builder settings
      • NuCache Settings
      • Package Migration
      • Plugins settings
      • Request handler settings
      • Rich text editor settings
      • Runtime minification settings
      • Runtime settings
      • Security Settings
      • Serilog settings
      • Tours settings
      • Type finder settings
      • Unattended
      • Web routing
    • Templating
      • Macros
        • Managing macros
        • Partial View Macros
      • Models Builder
        • Introduction
        • Configuration
        • Builder Modes
        • Understand and Extend
        • Using Interfaces
        • Tips and Tricks
      • Working with MVC
        • Working with MVC Views in Umbraco
        • View/Razor Examples
        • Using MVC Partial Views in Umbraco
        • Using View Components in Umbraco
        • Querying & Traversal
        • Creating Forms
    • Querying & Models
      • IMemberManager
      • IPublishedContentQuery
      • ITagQuery
      • UDI Identifiers
      • UmbracoContext helper
      • UmbracoHelper
      • IPublishedContent
        • IPublishedContent Collections
        • IPublishedContent IsHelpers
        • IPublishedContent Property Access & Extension Methods
    • Routing & Controllers
      • Routing requirements for backoffice authentication
      • Custom MVC controllers (Umbraco Route Hijacking)
      • Custom MVC Routes
      • URL Rewrites in Umbraco
      • Special Property Type aliases for routing
      • URL Redirect Management
      • Routing in Umbraco
        • FindPublishedContentAndTemplate()
        • IContentFinder
        • Inbound request pipeline
        • Outbound request pipeline
        • Published Content Request Preparation
      • Surface controllers
        • Surface controller actions
      • Umbraco API Controllers
        • Umbraco Api - Authorization
        • Umbraco Api - Routing & Urls
    • Searching
      • Examine
        • Examine Management
        • Examine Manager
        • Custom indexing
        • PDF indexes and multisearchers
        • quick-start
    • Using Notifications
      • Notification Handler
      • CacheRefresher Notifications Example
      • ContentService Notifications Example
      • Creating And Publishing Notifications
      • Determining if an entity is new
      • MediaService Notifications Example
      • MemberService Notifications Example
      • Sending Allowed Children Notification
      • Umbraco Application Lifetime Notifications
      • EditorModel Notifications
        • Customizing the "Links" box
    • Inversion of Control / Dependency injection
    • Management
      • Models Reference
        • Content
        • ContentType
        • DataType
        • DictionaryItem
        • Language
        • Media
        • MediaType
        • Relation
        • RelationType
        • ServerRegistration
        • Template
      • Services Reference
        • AuditService
        • ConsentService
        • DataTypeService
        • DomainService
        • EntityService
        • ExternalLoginService
        • FileService
        • MacroService
        • MediaService
        • MemberGroupService
        • MemberService
        • MemberTypeService
        • NotificationService
        • PackagingService
        • PublicAccessService
        • RedirectUrlService
        • RelationService
        • ServerRegistrationService
        • TagService
        • TextService
        • ContentService
          • Create content programmatically
        • ContentTypeService
          • Retrieving content types
          • Retrieving content types
        • LocalizationService
          • Retrieving languages
        • UserService
          • Creating a user
    • Plugins
      • Creating Resolvers
      • Finding types
    • Cache & Distributed Cache
      • Accessing the cache
      • ICacheRefresher
      • IServerMessenger
      • Getting/Adding/Updating/Inserting Into Cache
      • Examples
        • Working with caching
    • Response Caching
    • Security
      • Linking External Login Provider accounts
      • BackOfficeUserManager and Events
      • Cookies
      • Replacing the basic username/password check
      • External login providers
      • Locking of Users and password reset
      • Reset admin password
      • Umbraco Security Hardening
      • Umbraco Security Settings
      • Sensitive data
      • Sanitizing the Rich Text Editor
      • Setup Umbraco for a FIPS Compliant Server
      • HTTPS
      • Two-factor Authentication
      • Server-side file validation
    • Scheduling
    • Common Pitfalls & Anti-Patterns
    • API Documentation
    • Debugging with SourceLink
    • Language Variation
    • UmbracoMapper
    • Distributed Locks
    • AngularJS
      • Directives
        • umbLayoutSelector
        • umbLoadIndicator
        • umbProperty
      • Services
        • Editor Service
        • Events Service
          • changeTitle
  • Tutorials
    • Overview
    • Creating a Basic Website
      • Getting Started
      • Document Types
      • Creating Your First Template
      • CSS and Images
      • Displaying the Document Type Properties
      • Creating a Master Template
      • Creating Pages and Using the Master Template
      • Setting the Navigation Menu
      • Articles and Article Items
      • Adding Language Variants
      • Conclusions
    • Creating a Custom Dashboard
    • Creating a Property Editor
      • Adding configuration to a property editor
      • Integrating services with a property editor
      • Adding server-side data to a property editor
    • Creating a Multilingual Site
    • Add Google Authentication
    • Add Microsoft Entra ID authentication (Members)
    • The Starter Kit
      • Lessons
        • Customize the Starter Kit
        • Add a Blog Post Publication Date
          • Add a Blog Post Publication Date
          • Add a Blog Post Publication Date
        • Add Open Graph
          • Add Open Graph - Step 1
          • Add Open Graph - Step 2
          • Add Open Graph - Step 3
          • Add Open Graph - Step 4
          • Add Open Graph - Summary
        • Ask For Help and Join the Community
    • Editor's Manual
      • Getting Started
        • Logging In and Out
        • Umbraco Interface
        • Creating, Saving and Publishing Content Options
        • Finding Content
        • Editing Existing Content
        • Sorting Pages
        • Moving a Page
        • Copying a Page
        • Deleting and Restoring Pages
      • Working with Rich Text Editor
      • Version Management
        • Comparing Versions
        • Rollback to a Previous Version
      • Media Management
        • Working with Folders
        • Working with Media Types
        • Cropping Images
      • Tips & Tricks
        • Refreshing the Tree View
        • Audit Trail
        • Notifications
        • Preview Pane Responsive View
        • Session Timeout
    • Multisite Setup
    • Member Registration and Login
    • Custom Views for Block List
    • Connecting Umbraco Forms and Zapier
    • Creating an XML Sitemap
    • Implementing Custom Error Pages
Powered by GitBook
On this page
  • Settings
  • Prevalues
  • Data Type Definition Example
  • Content Example
  • Uploading images
  • Set focal point
  • Crop and resize
  • Powered by ImageSharp.Web
  • Sample code
  • Example to output a "banner" crop from a cropper property with the property alias "customCropper"
  • Example to dynamically create a crop using the focal point - in this case 300 x 400px image
  • CSS background example to output a "banner" crop
  • Add values programmatically
  • Get all the crop urls for a specific image
  • Sample on how to change the format of the image
Edit on GitHub
Export as PDF
  1. Fundamentals
  2. Backoffice
  3. Property Editors
  4. Built-in Property Editors

Image Cropper

PreviousFile UploadNextLabel

Last updated 2 years ago

Returns: MediaWithCrops

Returns a path to an image, along with information about focal point and available crops.

When the Image Cropper is used on a Media Type the crops are shared between all usages of a Media Item. This is called global crops.

If the Image Cropper is used on a Document Type, the file and crops will be local to the Document.

Notice that it is possible make local crops on shared Media Items via the .

Settings

Prevalues

You can add, edit & delete crop presets the cropper UI can use.

Data Type Definition Example

Content Example

The Image Cropper provides a UI to upload an image, set a focal point on the image, and use predefined crops.

By default, images in the Image Cropper will be shown based on a set focal point and only use specific crops if they are available.

The Image Cropper comes with 3 modes:

  • Uploading an image

  • Setting a focal point

  • Cropping the image to predefined crops

Uploading images

The editor exposes a drop area for files. Select it to upload an image.

Set focal point

By default, the Image Cropper allows the editor to set a focal point on the uploaded image.

All the preset crops are shown to give the editor a preview of what the image will look like on the frontend.

Crop and resize

The editor can fit the crop to the image to ensure that the image is presented as intended.

Powered by ImageSharp.Web

Sample code

The Image Cropper comes with an API to generate crop URLs. You can also access the raw data directly as a dynamic object.

For rendering a cropped media item, the .GetCropUrl is used:

<img src="@Url.GetCropUrl(Model.Photo,"square", true)" />

The third parameter is HtmlEncode and is by default set to true. This means you only need to define the parameter if you want to disable HTML encoding.

Example to output a "banner" crop from a cropper property with the property alias "customCropper"

<img src="@Url.GetCropUrl(Model.SecondaryPhoto, "customCropper", "banner")" />

Or, alternatively using the MediaWithCrops extension method:

<img src="@Model.SecondaryPhoto.GetCropUrl("customCropper", "banner")" />

Example to dynamically create a crop using the focal point - in this case 300 x 400px image

@if (Model.Photo is not null)
{
    <img src="@Url.GetCropUrl(Model.Photo, height: 300, width: 400)" alt="@Model.Photo.Name" />
}

CSS background example to output a "banner" crop

Set the htmlEncode to false so that the URL is not HTML encoded

@if (Model.Photo is not null)
{
    var cropUrl = Url.GetCropUrl(Model.Photo, "square", false);
    <style>
        .myCssClass {
            background-image: url("@cropUrl");
            height: 400px;
            width: 400px;
        }
    </style>
    <div class="product-image-container myCssClass"></div>
}

Add values programmatically

The following sample demonstrates how to add or change the value of an Image Cropper property programmatically. The sample creates an API controller with an action, which must be invoked via a POST request to the URL written above the action.

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PropertyEditors.ValueConverters;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.Common.Controllers;
using Umbraco.Extensions;

namespace Umbraco.Docs.Samples.Web.Property_Editors_Add_Values;

public class CreateImageCropperValuesController : UmbracoApiController
{
    private readonly IContentService _contentService;
    private readonly IMediaService _mediaService;
    private readonly MediaUrlGeneratorCollection _mediaUrlGeneratorCollection;


    public CreateImageCropperValuesController(
        IContentService contentService,
        IMediaService mediaService,
        MediaUrlGeneratorCollection mediaUrlGeneratorCollection)
    {
        _contentService = contentService;
        _mediaService = mediaService;
        _mediaUrlGeneratorCollection = mediaUrlGeneratorCollection;
    }

    // /Umbraco/Api/CreateImageCropperValues/CreateImageCropperValues
    [HttpPost]
    public ActionResult<bool> CreateImageCropperValues()
    {
        // Create a variable for the GUID of the page you want to update
        var contentKey = Guid.Parse("89974f8b-e213-4c32-9f7a-40522d87aa2f");

        // Get the page using the GUID you've defined
        IContent? content = _contentService.GetById(contentKey);
        if (content == null)
        {
            return false;
        }

        // Create a variable for the GUID of the media item you want to use
        var mediaKey = Guid.Parse("b6d4e98a-07c0-45f9-bfcc-52994f2806b6");

        // Get the desired media file
        IMedia? media = _mediaService.GetById(mediaKey);
        if (media == null)
        {
            return false;
        }

        // Create a variable for the image cropper and set the source
        var imageCropperValue = new ImageCropperValue
        {
            Src = media.GetUrl("umbracoFile", _mediaUrlGeneratorCollection)
        };

        // Serialize the image cropper value
        var propertyValue = JsonConvert.SerializeObject(imageCropperValue);

        // Set the value of the property with alias "cropper"
        // - remember to add the "culture" parameter if "cropper" is set to vary by culture
        content.SetValue("cropper", propertyValue);

        return _contentService.Save(content).Success;
    }
}
using System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PropertyEditors.ValueConverters;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.Common.Controllers;
using Umbraco.Extensions;

namespace Umbraco.Docs.Samples.Web.Property_Editors_Add_Values
{
    public class CreateImageCropperValuesController : UmbracoApiController
    {
        private IContentService _contentService;
        private IMediaService _mediaService;
        private MediaUrlGeneratorCollection _mediaUrlGeneratorCollection;


        public CreateImageCropperValuesController(IContentService contentService, IMediaService mediaService, MediaUrlGeneratorCollection mediaUrlGeneratorCollection)
        {
            _contentService = contentService;
            _mediaService = mediaService;
            _mediaUrlGeneratorCollection = mediaUrlGeneratorCollection;
        }

        // /Umbraco/Api/CreateImageCropperValues/CreateImageCropperValues
        [HttpGet]
        public ActionResult<string> CreateImageCropperValues()
        {
            // Create a variable for the GUID of the page you want to update
            var guid = Guid.Parse("4e96411a-b8e1-435f-9322-2faee30ef5f2");

            // Get the page using the GUID you've defined
            var content = _contentService.GetById(guid); // ID of your page

            // Create a variable for the GUID of the media item you want to use
            var mediaKey = Guid.Parse("cf1ab8dc-ad0f-4a8e-974b-87b84777b0d6");

            // Get the desired media file
            var media = _mediaService.GetById(mediaKey);

            // Create a variable for the image cropper and set the source
            var cropper = new ImageCropperValue {Src = media.GetUrl("umbracoFile", _mediaUrlGeneratorCollection)};

            // Serialize the image cropper value
            var cropperValue = JsonConvert.SerializeObject(cropper);

            // Set the value of the property with alias 'cropper'
            content.SetValue("testCropper", cropperValue, "en-US");

            return _contentService.Save(content).Success.ToString();
        }
    }
}

If you use Models Builder to generate source code (modes SourceCodeAuto or SourceCodeManual), you can use nameof([generated property name]) to access the desired property without using a magic string:

// Set the value of the "Cropper" property on content of type MyContentType
// - remember to add the "culture" parameter if "cropper" is set to vary by culture
content.SetValue(nameof(MyContentType.Cropper).ToFirstLowerInvariant(), propertyValue);
@{
    // Set the value of the property with alias 'cropper'
    content.SetValue(Product.GetModelPropertyType(_publishedSnapshotAccessor, x => x.TestCropper).Alias, cropperValue, "en-US");
}

Get all the crop urls for a specific image

Crop URLs are not limited to usage within a view. IPublishedContent has a GetCropUrl extension method, which can be used to access crop URLs anywhere.

The following sample demonstrates how to use GetCropUrl to retrieve URLs for all crops defined on a specific image:

public Dictionary<string, string> GetCropUrls(IPublishedContent image)
{
    // Get the Image Cropper property value for property with alias "umbracoFile"
    ImageCropperValue? imageCropperValue = image.Value<ImageCropperValue>("umbracoFile");
    if (imageCropperValue?.Crops == null)
    {
        return new Dictionary<string, string>();
    }

    // Return all crop aliases and their corresponding crop URLs as a dictionary
    var cropUrls = new Dictionary<string, string>();
    foreach (ImageCropperValue.ImageCropperCrop crop in imageCropperValue.Crops)
    {
        // Get the cropped URL and add it to the dictionary that I will return
        var cropUrl = crop.Alias != null
            ? image.GetCropUrl(crop.Alias)
            : null;
        if (cropUrl != null)
        {
            cropUrls.Add(crop.Alias!, cropUrl);
        }
    }

    return cropUrls;
}
internal Dictionary<string, string> GetCropUrls(IPublishedContent image)
{
    //Instantiate the dictionary that I will return with "Crop alias" and "Cropped URL"
    Dictionary<string, string> cropUrls = new Dictionary<string, string>();

    if (image.HasValue("umbracoFile"))
    {
        var imageCropper = image.Value<ImageCropperValue>("umbracoFile");
        foreach (var crop in imageCropper.Crops)
        {
            //Get the cropped URL and add it to the dictionary that I will return
            cropUrls.Add(crop.Alias, image.GetCropUrl(crop.Alias));
        }
    }

    return cropUrls;
}

Sample on how to change the format of the image

<img src="@Url.GetCropUrl(Model.Photo, 500, 300, furtherOptions: "&format=png")" />

is image processing middleware for ASP.NET.

We bundle this package with Umbraco and you can therefore take full advantage of all its features for resizing and format changing. Learn more about the built in processing commands in .

To update a content property value you need the .

Below the example to output a PNG using ImageSharp.Web command.

ImageSharp.Web
the official ImageSharp documentation
Content Service
format
Media Picker Property Editor
Image Cropper Data Type Definition
Image Cropper Upload
Image Cropper Focal point
Image Cropper Crop