|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | +using Microsoft.AspNetCore.Mvc; |
| 3 | +using Resgrid.Framework; |
| 4 | +using Resgrid.Model; |
| 5 | +using Resgrid.Model.Services; |
| 6 | +using System; |
| 7 | +using System.IO; |
| 8 | +using System.Net.Mime; |
| 9 | +using System.Threading.Tasks; |
| 10 | + |
| 11 | +using Resgrid.Web.Services.Models; |
| 12 | +using Resgrid.Web.ServicesCore.Helpers; |
| 13 | +using SixLabors.ImageSharp; |
| 14 | +using SixLabors.ImageSharp.Processing; |
| 15 | + |
| 16 | + |
| 17 | +namespace Resgrid.Web.Services.Controllers.v4 |
| 18 | +{ |
| 19 | + /// <summary> |
| 20 | + /// Used to interact with the user avatars (profile pictures) in the Resgrid system. The authentication header isn't required to access this method. |
| 21 | + /// </summary> |
| 22 | + [Route("api/v{VersionId:apiVersion}/[controller]")] |
| 23 | + [ApiVersion("4.0")] |
| 24 | + [ApiExplorerSettings(GroupName = "v4")] |
| 25 | + //[EnableCors("_resgridWebsiteAllowSpecificOrigins")] |
| 26 | + public class AvatarsController : ControllerBase |
| 27 | + { |
| 28 | + private readonly IImageService _imageService; |
| 29 | + private static byte[] _defaultProfileImage; |
| 30 | + |
| 31 | + public AvatarsController(IImageService imageService) |
| 32 | + { |
| 33 | + _imageService = imageService; |
| 34 | + } |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Get a users avatar from the Resgrid system based on their ID |
| 38 | + /// </summary> |
| 39 | + /// <param name="id">ID of the user</param> |
| 40 | + /// <returns></returns> |
| 41 | + [HttpGet("Get")] |
| 42 | + [Produces(MediaTypeNames.Image.Jpeg)] |
| 43 | + [ProducesResponseType(StatusCodes.Status200OK)] |
| 44 | + [ProducesResponseType(StatusCodes.Status404NotFound)] |
| 45 | + public async Task<ActionResult> Get(string id, int? type) |
| 46 | + { |
| 47 | + byte[] data = null; |
| 48 | + if (type == null) |
| 49 | + data = await _imageService.GetImageAsync(ImageTypes.Avatar, id); |
| 50 | + else |
| 51 | + data = await _imageService.GetImageAsync((ImageTypes)type.Value, id); |
| 52 | + |
| 53 | + if (data == null || data.Length <= 0) |
| 54 | + return File(GetDefaultProfileImage(), "image/png"); |
| 55 | + |
| 56 | + return File(data, "image/jpeg"); |
| 57 | + } |
| 58 | + |
| 59 | + [HttpPost("Upload")] |
| 60 | + [ProducesResponseType(StatusCodes.Status200OK)] |
| 61 | + [ProducesResponseType(StatusCodes.Status201Created)] |
| 62 | + [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| 63 | + public async Task<ActionResult> Upload([FromQuery] string id, int? type) |
| 64 | + { |
| 65 | + var img = HttpContext.Request.Form.Files.Count > 0 ? |
| 66 | + HttpContext.Request.Form.Files[0] : null; |
| 67 | + |
| 68 | + // check for a valid mediatype |
| 69 | + if (!img.ContentType.StartsWith("image/")) |
| 70 | + return BadRequest(); |
| 71 | + |
| 72 | + // load the image from the upload and generate a new filename |
| 73 | + //var image = Image.FromStream(img.OpenReadStream()); |
| 74 | + var extension = Path.GetExtension(img.FileName); |
| 75 | + byte[] imgArray; |
| 76 | + int width = 0; |
| 77 | + int height = 0; |
| 78 | + |
| 79 | + using (Image image = Image.Load(img.OpenReadStream())) |
| 80 | + { |
| 81 | + //image.Mutate(x => x |
| 82 | + // .Resize(image.Width / 2, image.Height / 2) |
| 83 | + // .Grayscale()); |
| 84 | + |
| 85 | + width = image.Width; |
| 86 | + height = image.Height; |
| 87 | + |
| 88 | + MemoryStream ms = new MemoryStream(); |
| 89 | + await image.SaveAsPngAsync(ms); |
| 90 | + imgArray = ms.ToArray(); |
| 91 | + |
| 92 | + //image.Save()"output/fb.png"); // Automatic encoder selected based on extension. |
| 93 | + } |
| 94 | + |
| 95 | + //ImageConverter converter = new ImageConverter(); |
| 96 | + //byte[] imgArray = (byte[])converter.ConvertTo(image, typeof(byte[])); |
| 97 | + |
| 98 | + if (type == null) |
| 99 | + await _imageService.SaveImageAsync(ImageTypes.Avatar, id, imgArray); |
| 100 | + else |
| 101 | + await _imageService.SaveImageAsync((ImageTypes)type.Value, id, imgArray); |
| 102 | + |
| 103 | + var baseUrl = Config.SystemBehaviorConfig.ResgridApiBaseUrl; |
| 104 | + |
| 105 | + string url; |
| 106 | + |
| 107 | + if (type == null) |
| 108 | + url = baseUrl + "/api/v4/Avatars/Get?id=" + id; |
| 109 | + else |
| 110 | + url = baseUrl + "/api/v4/Avatars/Get?id=" + id + "&type=" + type.Value; |
| 111 | + |
| 112 | + var obj = new |
| 113 | + { |
| 114 | + status = CroppicStatuses.Success, |
| 115 | + url = url, |
| 116 | + width = width, |
| 117 | + height = height |
| 118 | + }; |
| 119 | + |
| 120 | + return CreatedAtAction(nameof(Upload), new { id = obj.url }, obj); |
| 121 | + } |
| 122 | + |
| 123 | + [HttpPut("Crop")] |
| 124 | + [ProducesResponseType(StatusCodes.Status200OK)] |
| 125 | + [ProducesResponseType(StatusCodes.Status201Created)] |
| 126 | + [ProducesResponseType(StatusCodes.Status400BadRequest)] |
| 127 | + [ProducesResponseType(StatusCodes.Status500InternalServerError)] |
| 128 | + public async Task<ActionResult> Crop([FromBody] CropRequest model) |
| 129 | + { |
| 130 | + // extract original image ID and generate a new filename for the cropped result |
| 131 | + var originalUri = new Uri(model.imgUrl); |
| 132 | + var originalId = originalUri.Query.Replace("?id=", ""); |
| 133 | + |
| 134 | + try |
| 135 | + { |
| 136 | + byte[] imgArray; |
| 137 | + |
| 138 | + using (var ms = new MemoryStream(await _imageService.GetImageAsync(ImageTypes.Avatar, originalId))) |
| 139 | + using (var image = Image.Load(ms)) |
| 140 | + { |
| 141 | + // load the original picture and resample it to the scaled values |
| 142 | + var bitmap = ImageUtils.Resize(image, (int)model.imgW, (int)model.imgH); |
| 143 | + |
| 144 | + var croppedBitmap = ImageUtils.Crop(bitmap, model.imgX1, model.imgY1, model.cropW, model.cropH); |
| 145 | + |
| 146 | + using (var ms2 = new MemoryStream()) |
| 147 | + { |
| 148 | + await croppedBitmap.SaveAsPngAsync(ms2); |
| 149 | + imgArray = ms2.ToArray(); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + await _imageService.SaveImageAsync(ImageTypes.Avatar, originalId, imgArray); |
| 154 | + } |
| 155 | + catch (Exception ex) |
| 156 | + { |
| 157 | + Logging.LogException(ex, $"Error cropping avatar image for ID: {originalId}"); |
| 158 | + return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while cropping the image"); |
| 159 | + } |
| 160 | + |
| 161 | + var obj = new |
| 162 | + { |
| 163 | + status = CroppicStatuses.Success, |
| 164 | + url = originalId |
| 165 | + }; |
| 166 | + |
| 167 | + return CreatedAtAction(nameof(Crop), new { id = obj.url }, obj); |
| 168 | + } |
| 169 | + |
| 170 | + private byte[] GetDefaultProfileImage() |
| 171 | + { |
| 172 | + if (_defaultProfileImage == null) |
| 173 | + _defaultProfileImage = EmbeddedResources.GetApiRequestFile(typeof(AvatarsController), "Resgrid.Web.Services.Properties.Resources.defaultProfile.png"); |
| 174 | + |
| 175 | + return _defaultProfileImage; |
| 176 | + } |
| 177 | + } |
| 178 | + |
| 179 | + internal static class CroppicStatuses |
| 180 | + { |
| 181 | + public const string Success = "success"; |
| 182 | + public const string Error = "error"; |
| 183 | + } |
| 184 | +} |
0 commit comments