I am beginner to ASP.NET MVC 4 ... I want to upload images from my form and save them into the SQL database by using Entity Framework. I have searched a lot but couldn't succeed yet,,
-
2This will help you: stackoverflow.com/questions/19185848/… [Uplopad and Fetch image in mvc][1] [1]: stackoverflow.com/questions/19185848/…Ni3– Ni32014-04-08 11:45:27 +00:00Commented Apr 8, 2014 at 11:45
-
Please include some code to show us what you've tried.xdumaine– xdumaine2014-04-08 13:05:08 +00:00Commented Apr 8, 2014 at 13:05
-
At the risk of starting a flame war, unless you have a very specific business case that requires images actually be stored in the database, refrain from doing so. Pulling an image from a database for display on the web requires spinning up the entire ASP.NET framework just to serve the image, where as a static reference to an image allows IIS to serve it directly. Also, you'll have zero ability to optimize resource handling through things like CDNs, etc.Chris Pratt– Chris Pratt2014-04-08 13:58:14 +00:00Commented Apr 8, 2014 at 13:58
Add a comment
|
1 Answer
First Convert image into bytes and then assign generated bytes of the property of you model.
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
and then
YourModel obj = new YourModel()
obj.Image = imageToByteArray(image);
yourDbContext.YourModels.Add(obj);
yourDbContext.Savechanges()
Edited: From Byte[] to image
public Image byteArrayToImage(byte[] byteArrayIn)
{
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
returnImage = Image.FromStream(ms);
}
return returnImage;
}
2 Comments
Beginer Programer
How to retrieve image after saving this?
Ishtiaq
Convert back the bytes to Image. I have edited the answer accordingly.