2
I’m trying to display an image that’s stored in the database. When the Photo (Image) field of the table is null, I display a default image that is stored in the directory. The problem is that the images coming from the bank are not being displayed.
The Action that is exhibiting the treatment is below:
[HttpGet]
public FileContentResult ShowFoto(int? id)
{
byte[] fileBytes = null;
string fileType = null;
try
{
var terapeuta = db.TERAPEUTAs.Find(id); // Busca a imagem no Banco
if (terapeuta != null)
{
if (terapeuta.FOTO != null)
{
fileBytes = terapeuta.FOTO; // do tipo byte[]
fileType = System.Drawing.Imaging.ImageFormat.Jpeg.ToString(); // Tipo da Foto
return File(fileBytes, fileType);
}
else
{
Image img = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/img/SemFoto.jpg"));
return File(imageToByteArray(img), System.Drawing.Imaging.ImageFormat.Jpeg.ToString());
}
}
else
{
Image img = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/img/SemFoto.jpg"));
return File(imageToByteArray(img), System.Drawing.Imaging.ImageFormat.Jpeg.ToString());
}
}
catch(Exception ex)
{
throw ex;
}
}
The View code for displaying the image is below:
@using (Html.BeginForm("Buscar", "Terapeutas", FormMethod.Post, htmlAttributes: new { @id = "form1", @name = "form1" }))
{
@Html.ValidationSummary(true)
foreach (var item in Model.Terapeutas)
{
<img src="/Terapeutas/[email protected]_TERAPEUTA" class="img-circle" alt="Foto Terapeuta" width="120" height="120" /> }
}
}
Are you saving image directly in the database? Why not save to the project root and put in the database only the address where the image is? Wouldn’t it be simpler?
– Marconi
@Marconi, I need this image stored in the database. I have another project that does exactly what I want, and I copied the code from there. The problem is that in this new project the image is not being displayed, and I have no idea why.
– Gleison França
I think the image inside the bank record is broken. You have how to check this?
– Leonel Sanches da Silva
@Ciganomorrisonmendez how can I do this kind of checking? I searched for broken images on google and did not find relevant content. But if the fault is at the time of storing the image in the bank, it may be that the fault is in the code. This code snippet I use to upload to the database.
– Gleison França
using (Memorystream memoryStream = new Memorystream()) {
 vmterapeuta.FotoPerfil.InputStream.CopyTo(memoryStream, vmterapeuta.FotoPerfil.ContentLength);
 
 Stream fileStream = vmterapeuta.FotoPerfil.InputStream;
 byte[] fotoBytes = new byte[fileStream.Length]; fileStream.Read(fotoBytes, 0, fotoBytes.Length); objTerapeuta.FOTO = fotoBytes; }
– Gleison França
Have you tried logging into the bank using a tool and make a
select
in the table to check the contents?– Leonel Sanches da Silva
@Ciganomorrisonmendez Yes, the contents of the Photo column are filled with the byte array.
– Gleison França