Reputation: 2577
I need to display an online repository of images in my C# MVC 5 project. I tried with this tag,
<img src="@Url.Content(onlinePath)" alt="myImagetitle" />
This works if I have images inside folder of my project, but this is not working for online images, neither this is working if I give local disk path in it.
Upvotes: 0
Views: 1071
Reputation: 6683
This is a complete solution. This works even if the URL is not directly an image. For instance, the URL might be an API which return an image.
You need to get image as stream, then convert it to base64 string and then show on View:
Create a utility method like this:
public static string GetImageFromUrl(string url)
{
try
{
var request = WebRequest.Create(url);
request.Timeout = 3000; // optional
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (response.ContentType.Contains("image/"))
{
var imageBytes = new byte[response.ContentLength];
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
imageBytes = memoryStream.ToArray();
}
string imgBase64Data = Convert.ToBase64String(imageBytes);
return $"data:{response.ContentType};base64,{imgBase64Data}";
}
}
}
}
catch
{
// you can throw or ignore
}
return null;
}
In controller, you should have a string property in your model, or you can use ViewBag. I am using ViewModel.
model.Photo = Utility.GetImageFromUrl("https://url-to-your-image");
In Razor view do this:
@if (!string.IsNullOrWhiteSpace(Model.Photo))
{
<img src="@Model.Photo" />
}
If you inspect or (view source) in browser your view, it should appear like this:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAE.....">
Note that the static method also detects the format of the image.
Upvotes: 0
Reputation: 2577
I resolved the issue with the help of @Div, so here was the issue, my URL was missing http:// so when I appended this in the start of my dynamic URL it is working now and there is no need of @Url.Content() as this is already a URL.
Upvotes: 0
Reputation: 17004
Just use
<img src="@onlinePath" alt="myImagetitle" />
this.Url
is only a UrlHelper, which helps to generate a internal URL. In your case, you already have a URL.
Upvotes: 1