Search code examples
imageoutputstreamnancy

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.


Solution

  • 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