1

i have image value in database of type "image". in view saved under type byte[] i want to show it as image in my asp.net mvc view. the best its just as image. value if image is saved under Model.ImageData.

i tried to solve it like this:

<img height="450px" width="330px" src="<%= historyItem.ImageData %>" alt="image" />

but it doesnt work. how to do that?

4 Answers 4

6

The problem with your approach is that you have included the image data as part of your view model but the <img> tag expects an URL in the src attribute. Some browsers support base64 embedded images to be put inside the HTML but I would recommend you to avoid this approach as the volume of your markup might grow.

So you will need a controller action which serves the image:

public ActionResult Image()
{
    byte[] imageData = ...
    return File(imageData, "image/png");
}

and then point the src attribute of the img tag to this controller action:

<img height="450px" width="330px" src="<%= Url.Action("Image") %>" alt="image" />
Sign up to request clarification or add additional context in comments.

3 Comments

@Daniel A. White, haven't I? That's the second argument of the File method.
Well imageData might represent a JPG or GIF.
@Daniel A. White, sure, thought this was obvious.
0

There may be a solution with embedded images. But aside from this, you need to create another action to download the image:

<img height="450px" width="330px" 
     src="<%: Url.Action("Image", "Controller", new { id=Model.ImageId }) %>"
     alt="image" />

In the controller class:

public FileResult Image(int id)
{
  byte[] imageData = getImageBytes(id);
  string mimeType = getMimeType(id);

  return new FileStreamResult(new System.IO.MemoryStream(imageData), mimeType );
}

Comments

0

I'm no expert on ASP.NET. That said, can you cast it to an Image or a Bitmap?

On a WinForm or in the ASP.NET code behind, it would look something like....

Image img = historyItem.ImageData as Image;
if (img != null) {
  // Do Something
}

~Joe

Comments

0

You'll have to create a separate action method that returns a FileResult.

There should be lots of different questions on Stackoverflow on the subject. Try something from here:
https://stackoverflow.com/search?q=fileresult+mvc+image

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.