Please help.
I've been searching for hours now as I cannot display the image on the website. I'm using byte[] from database then return FileStreamResult in controller.
Below is my code
.cshtml
<img src="@Url.Action("GetImage", "User")" />
User Service
I was able to call the api with byte[] value.
public async Task<HttpResponseMessage> GetImage()
{
var client = _clientFactory.CreateClient("ApiName");
var response = await client.GetAsync(apiUrl);
return response;
}
Controller
[ResponseCache(Duration = 10)]
[HttpGet]
public async Task<IActionResult> GetImage()
{
var response = await _user.GetImage();
if (response.IsSuccessStatusCode)
{
var logo = await response.Content.ReadAsByteArrayAsync();
var ms = new MemoryStream(logo);
FileStreamResult result = new FileStreamResult(ms, "image/png");
result.FileDownloadName = "logo1223.png";
return result;
}
return null;
}
API
[HttpGet("logo")]
public async Task<IActionResult> GetImage()
{
var someByte= await GetSomeImage();
return Ok(someByte);
}
when I tried to download or save the image file I get this result.
Image is not loading from the website
UPDATE I tried to manually get the file then convert to byte[] and image is displaying properly on the website, I checked how they upload the image... I found out they are using below code to save image on DB.
var byteArr= Encoding.UTF8.GetBytes(Convert.ToBase64String(bArr.ToArray()))
Tried this modified controller
public async Task<FileContentResult> GetImage()
{
var img = Image.FromFile(@"C:\Downloads\test.png");
byte[] bArr = imgToByteArray(img);
var a = Encoding.UTF8.GetBytes(Convert.ToBase64String(bArr.ToArray()));
return File(bArr, "image/png"); // WORKING!!!
//return File(a, "image/png"); // NOT WORKING!!
}
Is there a way to convert it to original byte image?
The main issue is logo is saved in db using below code
var byteArr= Encoding.UTF8.GetBytes(Convert.ToBase64String(bArr.ToArray()))
Solution: Convert to original byte[] to get the image
[ResponseCache(Duration = 10)]
[HttpGet]
public async Task<IActionResult> GetImage()
{
var response = await _user.GetImage();
if (response.IsSuccessStatusCode)
{
// I created new class Logo which contains byte[] Logo
var logo = await response.Content.ReadAsAsync<Logo>();
// Convert to original byte[]
byte[] originalByte = Convert.FromBase64String(Encoding.UTF8.GetString(logo.Logo));
return File(originalByte, "image/png");
}
return null;
}