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?

2
  • 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. Commented Sep 17, 2018 at 7: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. Commented Sep 19, 2018 at 20:22

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

I never thought that you can convert byte array to image and pass it on src attribute. Cool way!
Just take care of how many images you are sending using the base64 encoding because you may get an outofmemory exception on server side.
Solution is working perfectly for me. Thank you @D-Shih for your guidance.

Your Answer

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