Reputation: 1817
Here is my model
public class MyModel
{
public System.Drawing.Image MyImage { get; private set; }
public MyModel(System.Drawing.Image myImage)
{
this.MyImage = myImage;
}
}
Here is my view
@model MyModel
@using MyNamespace.MyModels;
@{
ViewBag.Title = "title";
}
<img id="11111" src="@Model.MyImage" alt="Hello alt text" />
Here is my controller
public class MyController : Controller
{
public ActionResult Index()
{
Image img = GoAndGetImage(55);
MyModel model = new MyModel(img);
return View(model);
}
private System.Drawing.Image GoAndGetImage(int id)
{
// Retrieve bytesArray from sql db, convert to System.Drawing.Image type
}
}
But I only get to see Hello alt text and not the real image. What am I doing wrong?
Upvotes: 0
Views: 68
Reputation: 65049
You're trying to pass in an actual physical bitmap from memory.. into the page. This won't work.
You need to either:
a) Pass in a string path to the file. I.e:
this.MyImage = "/your/path/to/file.jpg";
...and...
src="@Model.MyImage"
b) Base64 encode the image and dump that to the page:
this.MyImage = base64String(ImageObject);
...and...
src="data:image/jpeg;base64,@Model.MyImage"
Either way.. MyImage
must be a string.
Here is an example of converting an in-memory image to base64: Converting image to base64
I will caution you from loading images from a database constantly. You'll quickly see your working set skyrocket if you have lots of users on your site. Its best to have the database as a lookup.. then check if the files exists on the file system. If it does, use the file on the file system. If it doesn't.. read it from the database and write it to the file system. Then you can continue loading that particular file from the filesystem in future.
Upvotes: 2
Reputation: 3985
The src
attribute has to be a URL pointing to the location of the image file, not an object of type System.Drawing.Image
.
Change your MyImage
property type to String
, set it to a relative (or absolute) path to where the image file is located and see if it works.
Upvotes: 1