ASP.NET MVC image from byte array - c#

currently I have a byte array representing my Image in my ViewModel. I display it with the following code:
<img src="#String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(Model.Image))" />
Now I don't want to have a Base64 String in my Source file, but rather a link to a image. Like:
<img src="Images/" + Model.Id"/>
which would return a Image.
How do I write such a method to return a Image link?

You could define a controller action that will serve the image:
public class ImagesController: Controller
{
public ActionResult Index(int id)
{
byte[] imageData = ... go get your image data from the id
return File(imageData, "image/png"); // Might need to adjust the content type based on your actual image type
}
}
and in your view simply point the src property of the img tag to this controller action:
<img src="#Url.Action("Index", "Images", new { id = Model.Id })" />

One way is to add this to a new c# class or HtmlExtensionsclass
public static class HtmlExtensions
{
public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
{
var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
return new MvcHtmlString("<img src='" + img + "' />");
}
}
then you can do this in any view
#Html.Image(Model.MyImageBytes)

Related

Trying to call and bind image in img src tag from server in mvc

Hi i'm trying to bind image in img tag in mvc .this tag is used in asp.net like this in the same way i want to bind image in MVC/
eg
ASP.net
<img alt="User Image" width="80px" height="80px" class="img img-thumbnail" src='<%="http://196.0.2.201/p001.ashx?pf=YY&cid="+Session[CommonConstants.SESSION_USER_ID] %>'/>
in mvc
I want to pass #ViewBag.session as parameter instead of Session[CommonConstants.SESSION_USER_ID] how to achieve it in Mvc any idea would be appreciated.
If you're using MVC why not base64 the image on the server while the page is being constructed and embed that in the image src for example with Razor:
<img src="data:image/jpeg;base64, #Model.Base64Image">
This way any logic used for generating the image is part of the same controller logic that is building your page.
Step by step:
your razor page will have a #model ViewModel Directive at the top and an image element somewhere that you are populating as above, the jpeg part can be any image type must must match the type that is being encoded.
your view model should have a string property in this case called Base64Image.
your controller should have a part that gets and converts the image e.g.
public IActionResult Index()
{
var model = new ViewModel();
// important thing here is to convert the image into a byte array:
var imageBytes = System.IO.File.ReadAllBytes(#"image.jpeg");
// Convert byte array to Base64 String
model.Base64Image = Convert.ToBase64String(imageBytes);
// return View model with base64 encoded image to page
return View(model);
}
the rendered page at the client side will have an image element something like this.
<img src="data:image/jpeg;base64, TWFuIGlzIGRpc3RpbmdR== ">
the base64 encoding will be hundreds of characters long.
Doing it this way the client doesn't need to make a second call to get the image its already in the page. What you're trying to do is define an endpoint that the client will call on to get the image.
Declare a new model
public class ModelImg
{
public int MyProperty1 { get; set; }
public bool MyProperty2 { get; set; }
public string Img { get; set; }
}
use your object in controller :
ModelImg model = new ModelImg(){Img = #"MyImgAsString",MyProperty1 = 1,MyProperty2 = true};
Assign your object or your img directly to a ViewData in your controller view:
ViewData["Img"] = model.Img;
In your View assign your src :
<img alt="User Image" width="80px" height="80px" class="img img-thumbnail" src='ViewData["Img"]'/>

Pass image from controller to View

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?
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?

Problems with Charting Display

I am having problems getting pie charts to display in my views correctly. With the code below, I have confirmed that bytes are being successfully written to the model and passed to the view. I have even confirmed that I can save the pie chart to a PNG file within a directory from the view, but every time I attempt to display the pie chart in the browser, no image is displayed.
You will see that I'm using an Index view with a Partial view for the Pie Chart. The plan is to present multiple partial views into the Index view.
I'm hoping someone can help me get past this. Thanks in advance.
Model:
public byte[] PieChartBytes { get; set; }
public class StatsForPieChart
{
public string dest { get; set; }
public long recordCount { get; set; }
}
Controller:
public ActionResult _DisplayPieChart (model.ViewModel model)
{
ArrayList xSeriesList = new ArrayList();
ArrayList ySeriesList = new ArrayList();
foreach (var item in model.statsforPieChart)
{
xSeriesList.Add(item.dest);
sSeriesList.Add(item.recordCount);
}
model.PieChartBytes = new Chart(width:800, height:600, theme: ChartThem.Blue)
.AddTitle("Title")
.AddLegend()
.AddSeries(
name: "Name",
chartType: "Pie",
xValue: xSeriesList,
yValues: ySeriesList)
.GetBytes("png");
return PartialView(model);
}
Index View:
Html.RenderAction("_DisplayPieChart", new { model = Model });
Pie Chart View:
#{
//the "Save" code is only used to prove the file bytes have been successfully passed and the image is present in the view:
string sImagePath = Server.MapPath("~") + "Content\\" + Guid.NewGuid().ToString + ".png"
WebImage myImage = new WebImage(Model.PieChartBytes);
myImage.Save(sImagePath);
}
<div class="text-center">
<img src="#sImagePath" /> //works in debug mode, but gets blocked on web server - not desired solution.
<img src="#myImage" /> //desired solution, but produces no image.
</div>
Where the image is just a string of bytes and not a file stored on a server anywhere, you need to prefix the bytes like this:
<img src="data:image/png;base64,#myImage" />
This is called a Data URL or Data URI
Additionally, though, I'm not sure you need to use WebImage here. You're already calling GetBytes() on the Chart object. That should return the bytes that you can use to display the image:
<img src="data:image/png;base64,#Model.PieChartBytes" />
Based on #Anonymous3521's comment, this code worked:
Controller:
var base64 = Convert.ToBase64String(Model.PieChartBytes);
var imgSrc = String.Format("data:image/png;base64,{0}", base64);
View:
<img src="#imgSrc" />

Write image to page with different name

I am trying to implement a simple captcha system and I wish to output an image without using its original name.
For example I would like to ouput the image file 8.gif to the page with the name captcha1.gif
I have read the various posts but I am looking for the simplest solution.
Here's what I have so far...
<% Html.RenderAction("OuputCaptchaImage", "Home", new { imageName = "1" }); %>
public ActionResult OuputCaptchaImage(string imageName)
{
var dir = Server.MapPath("images/");
var path = Path.Combine(dir, imageName + ".gif"); // Like to change name here
return base.File(path, "image/gif");
}
and what I would like to render to the page
<img src="image/captcha1.gif" />
The following mark-up will output the image correctly. However you still have the problem of the file name being referenced in the url.
<img src="<%= Url.Action("OuputCaptchaImage", "Home", new { imageName = "1" })%>" />
Which would output the following HTML:
<img src="/Home/OuputCaptchaImage?imageName=1" />
You could specify some other value as a parameter such as an enumeration rather than the image name, and then modify your logic to return the correct file.
However (AFAIK) to output an image with a file name which does not exist would require an Httphandler to intercept the request and write out the image you require to the response stream.
Edit
Here is an example of using an HttpHandler to intercept the incoming request for "captcha1.gif" and streaming a different image to the response:
Mark-up
<img src="Images/captcha1.gif" />
HttpHandler
public class OuputCaptchaImageHandler : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string imagePath =
context.Server.MapPath(#"~\Images\1.gif");
Bitmap bitmap = new Bitmap(imagePath);
context.Response.ContentType = "image/gif";
bitmap.Save(context.Response.OutputStream, ImageFormat.Gif);
bitmap.Dispose();
}
}
Web.Config
<httpHandlers>
<add verb="*" path="Images/captcha1.gif" type="FullyQualifiedNameSpace.OuputCaptchaImageHandler, RootNamespace" validate="false"></add>
</httpHandlers>
Global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("Images/captcha1.gif/{*pathInfo}");
....
Hope this helps.

How do I load an image from a database in ASP.NET MVC?

I have saved an image on the database and want to display it to the user.
The table the image is stored in looks like this:
Images
------
ImageData Byte
ImageName String
ContentType String
What should I do to load and show it in my View?
In Image controller class:
public ActionResult ProfileImage(string userName)
{
var imageByteArray = // get image bytes from DB corresponding to userName
string contentType = // get image content type from DB for example "image/jpg"
string fileName = // get image file name from DB
return File(imageByteArray, contentType, fileName);
}
In view:
<img src='/Image/ProfileImage/yourUserName' alt='Profile image' />
You'll also need a custom route in Global.asax:
routes.MapRoute(
"ProfileImage",
"Image/ProfileImage/{userName}",
new { controller = "Image", action = "ProfileImage", userName = "" }
);
You can also load the image in Bitmap and apply changes like resizing, rotation and so on. If you do that consider saving the image as png since GDI+ (System.Drawing) can keep best quality and transparency with this format. It is also good practice to cache dynamic images.

Categories

Resources