Returning an image from a General Handler in .NET

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:

Leave a message please

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.