Instantly share code, notes, and snippets.

Embed
What would you like to do?
Different ways of returning an ImageStream
// 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 :)
}
}
}
@labilbe

This comment has been minimized.

Show comment
Hide comment
@labilbe

labilbe Mar 8, 2018

Since IStreamWriter is obsolete now, how would you implement IStreamWriterAsync?

labilbe commented Mar 8, 2018

Since IStreamWriter is obsolete now, how would you implement IStreamWriterAsync?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment