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