2

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?

  • The best way for sending image from controller to view is just sending saved image URL as string and use it in src of img tag. Other approaches may have heavy process on server side. – Sajad Afaghiy Sep 17 '18 at 07:16
  • @SajadAfaghiy - Size of images change on different web pages in some requirements where code must resize an image to a different size than the saved size before displaying. `AspectRatio` method in my code maintains image aspect ratio while doing that. –  Sep 19 '18 at 20:22

1 Answers1

2

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?

D-Shih
  • 44,943
  • 6
  • 31
  • 51
  • I never thought that you can convert byte array to image and pass it on src attribute. Cool way! – Willy David Jr Sep 17 '18 at 07:09
  • 1
    Just take care of how many images you are sending using the base64 encoding because you may get an `outofmemory` exception on server side. – blfuentes Sep 17 '18 at 07:15
  • Solution is working perfectly for me. Thank you @D-Shih for your guidance. –  Sep 17 '18 at 07:26