Created
March 3, 2017 15:10
-
-
Save ajamaeen/cbfd657df36b30f00625d906393b43d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ImageMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
private readonly string _path; | |
public ImageMiddleware(RequestDelegate next, string path) | |
{ | |
_next = next; | |
this._path = path; | |
} | |
public async Task Invoke(HttpContext context) | |
{ | |
if (context.Request.Path.Equals(this._path, StringComparison.OrdinalIgnoreCase)) | |
{ | |
this.HandleImageRequest(context); | |
} | |
else | |
{ | |
await this._next.Invoke(context); | |
} | |
} | |
private async void HandleImageRequest(HttpContext context) | |
{ | |
var width = this.GetQueryStringValue(context, "w"); | |
var height = this.GetQueryStringValue(context, "h"); | |
var imageId = this.GetQueryStringValue(context, "id"); | |
if (imageId <= 0) | |
{ | |
throw new ArgumentNullException($"id : {imageId} must be greater than zero"); | |
} | |
if (width <= 0 || height <= 0) | |
{ | |
throw new ArgumentNullException($"Width : {width} && height : {height} must be greater than zero"); | |
} | |
var image = ImageManager.GetImage(imageId); | |
if (image != null) | |
{ | |
using (MagickImage magickImage = new MagickImage(image.ImageBinary)) | |
{ | |
if (magickImage.Height > height && magickImage.Width > width) | |
{ | |
magickImage.Resize(width, height); | |
} | |
var buffer = magickImage.ToByteArray(); | |
context.Response.Clear(); | |
context.Response.ContentType = image.MimeType; | |
await context.Response.Body.WriteAsync(buffer, 0, buffer.Length); | |
} | |
} | |
else | |
{ | |
context.Response.Clear(); | |
await context.Response.WriteAsync($"Image Not Found With ID {imageId}"); | |
} | |
} | |
private int GetQueryStringValue(HttpContext context, string prmName) | |
{ | |
int val = 0; | |
var wQuery = context.Request.Query[prmName]; | |
if (!string.IsNullOrWhiteSpace(wQuery)) | |
{ | |
int.TryParse(wQuery, out val); | |
} | |
return val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment