Pass image from controller to View

Viewed 1909

I'm trying to pass an image from controller to a view as:

Controller:

model.image = AspectRatio(String.Format("~" + i.ImageUrl));
return View(model);

Model:

public Bitmap image { get; set; }

View:

@model OnlineStore.ViewModels.ItemVM
<div>
    @Model.image
<div>

Code throwing no errors but instead of displaying image, browser is displaying following line of text:

System.Drawing.Bitmap

Can someone please guide?

1 Answers

Passing Bitmap instance to razor view that didn't show any image, because Hypertext Transfer Protocol, if you want to show images you might use img tag.

Model:

You can try to use byte array property imageBuffer, to carry your image data.

public byte[] imageBuffer { get; set; }

Controller:

use ImageConverter let Bitmap object image data to byte[]

ImageConverter converter = new ImageConverter();

Bitmap imageObj = AspectRatio(String.Format("~" + i.ImageUrl));

model.imageBuffer = (byte[])converter.ConvertTo(imageObj, typeof(byte[]));

return View(model);

View:

Convert.ToBase64String function let byte[] to base64 string. and img tag support display image by base64, just set src attribute and declare data:image/png;base64 in it.

because of img tag support base64 data

<img src="@String.Format("data:image/png;base64,{0}",Convert.ToBase64String(Model.imageBuffer))" />

Refer Link

what does this mean ? image/png;base64?

Related