Friday, February 26, 2010

How to return Images or Files with the HTTP Server (MFToolkit)

Is it somehow possible to have a static webpage with some images stored in Resources? I mean the web page can be treated just as string and sent to client, but i have been unable so far to send image file. I can get the image from resources

Bitmap image = Resources.GetBitmap(

But what to do then? how to read bytes from these image and send them to client? Or is there some other way? I don’t want to use SD card or anything external, that would be a waste of resources.

Well, if you add an image to the embedded resources (Resources.resx) Visual Studio will use it as a bitmap (see the example above). In older Micro .NET Framework it isn’t really easy to get the bytes from an image.

The best way to return images do following:

  1. Rename your image xxxx.jpg to xxxx.bin
  2. Open Resources.resx and select the type files (instead of type images)
  3. Click on add new file, select file filter *.*
  4. Select the image xxxx.bin which will be added as xxxx embedded resource

Then you can use following code in your HttpHandler:

if (context.Request.RawUrl == "/xxxx.jpg")
    context.Response.ContentType = "images/jpeg";

You can do the same with any static file as well as text files (*.html).

No comments: