How to show an image in the browser only having its contents (byte[])
I'm developing a MVC application and I need to show an image in the browser, but I haven't the file physically on disk.
I only have a byte[]
array in my model, with content of the image. Is there any "easy" trick to show the image in the view, without writing it to the disk?
The first approach that comes to my mind is writing a temp file, but:
- What file name should I choose?
- When should I delete it? I'm afraid that we will leak those files.
So I don't want to write the contents to a file. Is there any other approach?
Thanks in advanced.
EDIT: The result page is not only the image, I need to show some text, and below, the image, for example:
<%= Response.Write("Some text here") %>
&l开发者_运维问答t;%= /* Here my image */ %>
I'd create a controller action that returns the image from a byte array. In your view, you can use the normal <img>
tag, setting the src
attribute to your controller action that renders the image.
It would be something like this:
[HttpGet]
public ActionResult Render(...)
{
byte[] imageBytes = ...;
MemoryStream imageStream = new MemoryStream();
imageStream.Write(imageBytes, 0, imageBytes.Length);
return new FileStreamResult(imageStream, "image/png"); // might be a different mime type depending on your image type
}
From your View you can then do:
<p>Some text here</p>
<img src="<%= Url.Action("Render", "MyController", new { params as needed }) %>" alt="Image" />
Several options:
- Write a HTTP handler that will return the byte array and point the image URL to it
- Write a custom image controller and point the image URL to it
- Use the data URI scheme outputting the image data directly
- If you just want the image and are not serving up HTML, just stream it out with the correct headers
You can have a page that will serve image like that:
var context = System.Web.HttpContext.Current;
context.Response.Clear();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.End();
You should also set context.Response.ContentType
to something meaningful. If you use ImageEncoder to generate array of bytes, you can use its mimeType
property, if not - figure the way to provide a correct content-type (like "image/PNG"
)
精彩评论