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:
context.Response.ContentType = "image/" + System.Drawing.Imaging.ImageFormat.Jpeg;
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.
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();
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 –
- System.Drawing Namespace –
- ImageFormat Class –
- Image Class –