public
Last active

Different ways of returning an ImageStream

  • Download Gist
HelloImage.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// 3 different ways to return an image.
// More info about other responses http://stackoverflow.com/questions/6245616/does-servicestack-support-binary-responses
 
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using ServiceStack.Common.Web;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
 
namespace ServiceStack.WebHost.IntegrationTests.Services
{
[RestService("/HelloImage")]
public class HelloImage {}
 
public class HelloImageService : IService<HelloImage>
{
public object Execute(HelloImage request)
{
using (Bitmap image = new Bitmap(10, 10))
{
using (Graphics g = Graphics.FromImage(image))
{
g.Clear(Color.Red);
}
var ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
return new HttpResult(ms, "image/png"); //writes stream directly to response
}
}
}
 
[RestService("/HelloImage2")]
public class HelloImage2 {}
 
public class HelloImage2Service : IService<HelloImage2>
{
public object Execute(HelloImage2 request)
{
using (Bitmap image = new Bitmap(10, 10))
{
using (Graphics g = Graphics.FromImage(image))
{
g.Clear(Color.Red);
}
using (MemoryStream m = new MemoryStream())
{
image.Save(m, ImageFormat.Png);
var imageData = m.ToArray(); //buffers
return new HttpResult(imageData, "image/png");
}
}
}
}
 
[RestService("/HelloImage3")]
public class HelloImage3 {}
 
//Your own re-usable Custom ImageResult, writes directly to response stream
public class ImageResult : IDisposable, IStreamWriter, IHasOptions
{
private readonly Image image;
private readonly ImageFormat imgFormat;
 
public ImageResult(Image image, ImageFormat imgFormat=null)
{
this.image = image;
this.imgFormat = imgFormat ?? ImageFormat.Png;
this.Options = new Dictionary<string, string> {
{ HttpHeaders.ContentType, "image/" + this.imgFormat.ToString().ToLower() }
};
}
 
public void WriteTo(Stream responseStream)
{
image.Save(responseStream, imgFormat); //Writes to response stream here
}
 
public void Dispose()
{
this.image.Dispose();
}
 
public IDictionary<string, string> Options { get; set; }
}
 
public class HelloImage3Service : IService<HelloImage3>
{
public object Execute(HelloImage3 request)
{
var image = new Bitmap(10, 10);
using (var g = Graphics.FromImage(image))
g.Clear(Color.Red);
 
return new ImageResult(image); //terse + explicit is good :)
}
}
 
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.