ImageSharp is a new, fully featured, fully managed, cross-platform, 2D graphics API. Designed to democratize image processing, ImageSharp brings you an incredibly powerful yet beautifully simple API. [Ref]
Having an azure function for your image resizing needs ,thumbnails, can be quite handy whether in production or a dev environment.
Code sample for image resize by providing height and width:
using System.IO; using System.Numerics; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Drawing; using SixLabors.ImageSharp.Processing.Transforms; using SixLabors.Primitives; using SixLabors.Shapes; namespace AzureFuncSamples.ImageResize { public static class ImageResizeFunctions { public static byte[] GenerateThumbnailByWidthHeight(Image<Rgba32> image, int w, int h) { image.Mutate(x => x.Resize(w, h)); using (var returnImageStream = new MemoryStream()) { image.Save(returnImageStream, new JpegEncoder()); return returnImageStream.ToArray(); } } } }
Actual Azure Function:
using System.IO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Azure.WebJobs.Host; using SixLabors.ImageSharp; using Path = System.IO.Path; namespace AzureFuncSamples.ImageResize { public static class ImageResizer { [FunctionName("ImageResizeByWidthHeight")] public static IActionResult ImageResizeByWidthHeight([HttpTrigger(AuthorizationLevel.Anonymous, "post" , Route = "imageresize/{w=w}/{h=h}")]HttpRequest req, int w, int h, TraceWriter log) { using (var imageStream = Image.Load(req.Body)) { if ((w <= 0 || w > imageStream.Width) || (h <= 0 || h > imageStream.Height)) return new BadRequestObjectResult("Provide proper width and height"); return new FileContentResult(ImageResizeFunctions.GenerateThumbnailByWidthHeight(imageStream, w, h), "image/jpeg"); } } } }
And that’s it, neat and clean.
As ImageSharp is a cross-platform library, you can use this in .Net Framework ( Aps.net, WebApi) or .Net Core.
Complete code is available in my GitHub repo : azure-function-samples
This is does not work, I added PM> Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0006
To my project and no reference to ImageResizeFunctions.GenerateThumbnailByWidthHeight