Last Updated: 2019-03-31
Piranha has built in support for scaling and cropping uploaded images on demand. The new image is saved in the configured
storage so that it can be reused on subsequent requests. To enable image processing you need to register a service that implements
Via the MediaService
Images can be scaled by calling the MediaService.
// Scales the image to the given width
var scaledUrl = api.Media.EnsureVersion(id, width);
var scaledAsync = await api.Media.EnsureVersionAsync(id, width);
// Scales and crops the image to the given width & height
var scaledCroppedUrl = api.Media.EnsureVersion(id, width, height);
var scaledCroppedAsync = await api.Media.EnsureVersionAsync(id, width, height);
Please note that since the
IStorageSession interfaces are async, the synchronous versions of the methods are merely wrappers around the async versions.
Via the ApplicationService
ApplicationService provides wrappers for the methods available in the MediaRepository for usage in
.cshtml views. As the ApplicationServices has access to the current
IApi there's no need for injecting an Api when using the service.
@inject Piranha.AspNetCore.Services.IApplicationService WebApp
<img src="@Url.Content(WebApp.Media.ResizeImage(Model.PrimaryImage, 400))">
Via the ImageField
ImageField also has a method for scaling & cropping images. This is merely a wrapper for the methods available in the
MediaRepository but it can still be useful when calling from a
@inject Piranha.IApi Api
<img src="@Url.Content(Model.PrimaryImage.Resize(Api, 400))">