|
| 1 | +using System; |
| 2 | +using System.Threading.Tasks; |
| 3 | +using Microsoft.AspNetCore.Hosting; |
| 4 | +using Microsoft.AspNetCore.Mvc; |
| 5 | +using Microsoft.AspNetCore.NodeServices; |
| 6 | +using Microsoft.AspNetCore.StaticFiles; |
| 7 | + |
| 8 | +namespace NodeServicesExamples.Controllers |
| 9 | +{ |
| 10 | + public class ResizeImageController : Controller |
| 11 | + { |
| 12 | + private const int MaxDimension = 1000; |
| 13 | + |
| 14 | + private IHostingEnvironment _environment; |
| 15 | + private INodeServices _nodeServices; |
| 16 | + |
| 17 | + public ResizeImageController(IHostingEnvironment environment, INodeServices nodeServices) |
| 18 | + { |
| 19 | + _environment = environment; |
| 20 | + _nodeServices = nodeServices; |
| 21 | + } |
| 22 | + |
| 23 | + [Route("resize/{*imagePath}")] |
| 24 | + public async Task<IActionResult> Index(string imagePath, int maxWidth, int maxHeight) |
| 25 | + { |
| 26 | + // Validate incoming params |
| 27 | + if (maxWidth > MaxDimension || maxHeight > MaxDimension || (maxHeight <= 0 && maxWidth <= 0)) |
| 28 | + { |
| 29 | + return BadRequest("Invalid dimensions"); |
| 30 | + } |
| 31 | + |
| 32 | + // Locate source image on disk |
| 33 | + var fileInfo = _environment.WebRootFileProvider.GetFileInfo(imagePath); |
| 34 | + if (!fileInfo.Exists) |
| 35 | + { |
| 36 | + return NotFound(); |
| 37 | + } |
| 38 | + |
| 39 | + // Invoke Node and convert the base64 result back to bytes |
| 40 | + var mimeType = GetContentType(imagePath); |
| 41 | + var resizedImage = await _nodeServices.Invoke<ResizeImageResult>("./Node/resizeImage", fileInfo.PhysicalPath, mimeType, maxWidth, maxHeight); |
| 42 | + return File(Convert.FromBase64String(resizedImage.Base64), mimeType); |
| 43 | + } |
| 44 | + |
| 45 | + private string GetContentType(string path) |
| 46 | + { |
| 47 | + string result; |
| 48 | + if (!new FileExtensionContentTypeProvider().TryGetContentType(path, out result)) |
| 49 | + { |
| 50 | + result = "application/octet-stream"; |
| 51 | + } |
| 52 | + |
| 53 | + return result; |
| 54 | + } |
| 55 | + |
| 56 | + private class ResizeImageResult |
| 57 | + { |
| 58 | + public string Base64 { get; set; } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments