-
-
Save mahizsas/5e285a89de75b1a44c36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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