I need to convert byte array to image. I have stored image as byte array in my sql server database which I got as an argument of a method.
this is my db table:
Rid int
Name varchar
Email varchar
Photo Image
Given that your initial question is;
How can I convert byte array to image and display the image in a image controller in asp.net
I assume you are working with MVC. The easiest way is to create your controller like this;
public class ImageController : Controller
{
public ActionResult GetImage(int i)
{
byte[] bytes = db.GetImage(i); //Get the image from your database
return File(bytes, "image/png"); //or "image/jpeg", depending on the format
}
}
Then, in your view, simply use
<img src="@Url.Action("GetImage", "Image", new { id = Model.Id })" />
Where Model.Id
is the Id of the image.
There are other methods such as converting the image to a Base64-array and putting it in a model, for example;
public class YourModel
{
public int Id { get; set; }
public string ImageB64 { get; set; }
}
And in your controller;
public class YourController : Controller
{
public ActionResult YourView(int id)
{
var model = new YourModel();
var image = db.GetImage(id);
model.Id = id;
model.ImageB64 = String.Format("data:image/png;base64,{0}", Convert.ToBase64String(image));
return View(model);
}
}
And in your view;
<img src="@Model.ImageB64" />
But doing it like the above will not cache the image and will bloat your CSS. Generally this is not the best way to display images. Stick with the first option if possible.
Try this
// Lets assume you have taken image byte array into imageBytes variable
MemoryStream ms = new MemoryStream(imageBytes);
Image image= Image.FromStream(ms);
// Save the file into folder
image.Save(filename: "filename with path");
You could use Image.FromStream
and do something like this.
Image img;
using (var ms = new MemoryStream(bytes))
{
img= Image.FromStream(ms);
}