Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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