Skip to content

Instantly share code, notes, and snippets.

@darrelmiller
Created June 11, 2014 21:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save darrelmiller/6eb156c7d84559c4aa8d to your computer and use it in GitHub Desktop.
Save darrelmiller/6eb156c7d84559c4aa8d to your computer and use it in GitHub Desktop.
ImageContent
public class ImageContent : HttpContent
{
private Image _image;
public ImageContent(Image image, MediaTypeHeaderValue mediatype)
{
_image = image;
Headers.ContentType = mediatype;
}
protected async override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var format = GetFormat(Headers.ContentType);
_image.Save(stream, format);
_image.Dispose(); // Once sent or buffered, then throw away image
_image = null;
}
protected override bool TryComputeLength(out long length)
{
// If you really don't want to load it into a buffer,
// then you will need to chunk encoding it because you don't know it's length
length = -1;
return false;
}
private static ImageFormat GetFormat(MediaTypeHeaderValue mediatype)
{
ImageFormat format = null;
switch (mediatype.MediaType)
{
case "image/jpeg":
format = ImageFormat.Jpeg;
break;
case "image/png":
format = ImageFormat.Png;
break;
case "image/gif":
format = ImageFormat.Gif;
break;
case "image/tiff":
format = ImageFormat.Tiff;
break;
default:
throw new ArgumentException("Unsuppported media type");
}
return format;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment