Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an image handler in NancyFx

I'm struggling to output an Image from byte[] out of my database in NancyFX to a web output stream. I don't have sample code close enough to even show at this point. I was wondering if anyone has tackled this problem and could post a snippet? I basically just want to return image/jpeg from a byte array stored in my database and out put it to the web rather than a physical file.

like image 974
sethxian Avatar asked Jan 23 '13 06:01

sethxian


3 Answers

Just to build on @TheCodeJunkie's answer, you can build a "byte array response" very easily like this:

public class ByteArrayResponse : Response
{
    /// <summary>
    /// Byte array response
    /// </summary>
    /// <param name="body">Byte array to be the body of the response</param>
    /// <param name="contentType">Content type to use</param>
    public ByteArrayResponse(byte[] body, string contentType = null)
    {
        this.ContentType = contentType ?? "application/octet-stream";

        this.Contents = stream =>
            {
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(body);
                }
            };
    }
}

Then if you want to use the Response.AsX syntax it's a simple extension method on top:

public static class Extensions
{
    public static Response FromByteArray(this IResponseFormatter formatter, byte[] body, string contentType = null)
    {
        return new ByteArrayResponse(body, contentType);
    }
}

Then in your route you can just use:

Response.FromByteArray(myImageByteArray, "image/jpeg");

You could also add a processor to use a byte array with content negotiation, I've added a quick sample of that to this gist

like image 179
Steven Robbins Avatar answered Nov 16 '22 22:11

Steven Robbins


In your controller, return Response.FromStream with a stream of bytes of the image. It used to be called AsStream in older versions of nancy.

Get["/Image/{ImageID}"] = parameters =>
{
     string ContentType = "image/jpg";
     Stream stream = // get a stream from the image.

     return Response.FromStream(stream, ContentType);
};
like image 22
kristianp Avatar answered Nov 16 '22 23:11

kristianp


From Nancy you can return a new Response object. It's Content property is of type Action<Stream> so you can just create a delegate that writes your byte array to that stream

var r = new Response();
r.Content = s => {
   //write to s
};

Don't forget to set the ContentType property (you could use MimeTypes.GetMimeType and pass it the name, including extension) There is also a StreamResponse, that inherits from Response and provides a different constructor (for a bit nicer syntax you can use return Response.AsStream(..) in your route.. just syntax candy)

like image 8
TheCodeJunkie Avatar answered Nov 16 '22 22:11

TheCodeJunkie