You know how to return a string, you know how to return an integer and you know how to return JSON, but do you know how to return an image from a General Handler file (ashx) in .NET 4.6?
Well if not then fear not as I have the answer.
Simply put you make sure the return type is or an image:
C#
context.Response.ContentType = "image/" + System.Drawing.Imaging.ImageFormat.Jpeg;
VB
context.Response.ContentType = "image/" + System.Drawing.Imaging.ImageFormat.Png;
We then use the ‘Image’ class from the ‘System.Drawing’ namespace, which can be used in both VB and C#. With this item we can use the method ‘Save’ to instead of saving it to a file, we save it to the http requests ‘OutputStream’ as this is what will be returned to the user.
C#
Using System.Drawing;
## Get your image into the Image class via your own method
Image MyImage = GetImage();
## Save the Image to the OutputStream back to the request
MyImage.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
##Clean up after yourself
MyImage.Dispose();
VB
Import System.Drawing
' Get your image into the Image class via your own method
Dim MyImage As Image = GetImage()
' Save the Image to the OutputStream back to the request
MyImage.Save(context.Response.OutputStream, Imaging.ImageFormat.Jpeg)
' Clean up after yourself
MyImage.Dispose()
Here are some helpful links for some further reading:
- HttpContext Class –
https://msdn.microsoft.com/en-us/library/system.web.httpcontext(v=vs.110).aspx - System.Drawing Namespace –
https://msdn.microsoft.com/en-us/library/system.drawing(v=vs.110).aspx - ImageFormat Class –
https://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat(v=vs.110).aspx - Image Class –
https://msdn.microsoft.com/en-us/library/system.drawing.image(v=vs.110).aspx