Reputation: 101
I would like to to read an image from file or blob storage and base64 encode it as a stream and then pass that stream to StreamContent. The following code times out:
[HttpGet, Route("{id}", Name = "GetImage")]
public HttpResponseMessage GetImage([FromUri] ImageRequest request)
{
var filePath = HostingEnvironment.MapPath("~/Areas/API/Images/Mr-Bean-Drivers-License.jpg");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(filePath, FileMode.Open);
var cryptoStream = new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write);
result.Content = new StreamContent(cryptoStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
I am able to get the following code to work without keeping the file as a stream and read it all into memory but I would like to avoid that.
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
using (var image = Image.FromStream(fileStream))
{
var memoryStream = new MemoryStream();
image.Save(memoryStream, image.RawFormat);
byte[] imageBytes = memoryStream.ToArray();
var base64String = Convert.ToBase64String(imageBytes);
result.Content = new StringContent(base64String);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return result;
}
}
Upvotes: 1
Views: 615
Reputation: 21
The problem here is you're passing CryptoStreamMode.Write
to the constructor of CryptoStream
whereas you should be passing CryptoStreamMode.Read
because the CryptoStream
is going to be read as the HttpResponseMessage
is returned.
For more details about this, see Figolu's great explanation about the various usages of CryptoStream
in this answer.
Upvotes: 2