Foros del Web » Programando para Internet » ASPX (.net) »

Mostrar imagen desde SQL C#

Estas en el tema de Mostrar imagen desde SQL C# en el foro de ASPX (.net) en Foros del Web. hola tengo una funcion q rescate de internet pero lamentabblemente no me funciona al hacer el debug todo marcha bien pero cuando termina muestra como ...
  #1 (permalink)  
Antiguo 05/05/2010, 04:02
Avatar de jahman  
Fecha de Ingreso: noviembre-2003
Ubicación: Oslo
Mensajes: 230
Antigüedad: 20 años, 5 meses
Puntos: 0
Mostrar imagen desde SQL C#

hola tengo una funcion q rescate de internet pero lamentabblemente no me funciona al hacer el debug todo marcha bien pero cuando termina muestra como q la imagen no se encuentra....en la base de datos tengo un campo llamado Contents q es del tipo Image.


Default.aspx
Código:
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            connection = new SqlConnection(conn);

            connection.Open();
            string sql = "select TOP 1 ItemId from RubrikkImg.dbo.Attachment";
            SqlCommand cmd = new SqlCommand(sql, connection);
            int ItemId = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("ItemId is {0}", ItemId);

            // Display the image from the database
            Image1.ImageUrl = "~/ImgHandler.ashx?ItemId=" + ItemId;
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }
    }
ImgHandler.ashx
Código:
<%@ WebHandler Language="C#" Class="ImgHandler" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using RubrikkImg;
using System.Collections.Generic;

public class ImgHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       string empno;
       if (context.Request.QueryString["ItemId"] != null)
           empno = context.Request.QueryString["ItemId"].ToString();
       else
            throw new ArgumentException("No parameter specified");
 
       context.Response.ContentType = "jpeg/bmp";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
 
       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }       
       context.Response.BinaryWrite(buffer);
    }
 
    public Stream ShowEmpImage(string empno)
    {
        string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT Contents FROM RubrikkImg.dbo.Attachment WHERE ItemId = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[]) img);
        }
        catch
        {
            return null;
        }
        /*finally
        {
            connection.Close();
        }*/
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
 
}
  #2 (permalink)  
Antiguo 05/05/2010, 08:07
 
Fecha de Ingreso: octubre-2000
Mensajes: 1.692
Antigüedad: 23 años, 6 meses
Puntos: 19
Respuesta: Mostrar imagen desde SQL C#

Hola

Desde estos dos articulos puedes ver algo similar y bajarte el codigo fuente:

http://www.codeproject.com/KB/asp/Di...from_Data.aspx


http://www.beansoftware.com/ASP.NET-...-Database.aspx
__________________
PD: Con amor, fe, amor a Dios y amistad podemos hacer un mundo mejor!!!!
  #3 (permalink)  
Antiguo 05/05/2010, 08:19
Avatar de jahman  
Fecha de Ingreso: noviembre-2003
Ubicación: Oslo
Mensajes: 230
Antigüedad: 20 años, 5 meses
Puntos: 0
Respuesta: Mostrar imagen desde SQL C#

gracias por responder

uff no sabes todos los codigo q he intentado el primero e me diste es igual q este http://www.codeproject.com/KB/aspnet...nDatabase.aspx sol q este esta en c# y el segundo lo intente pero no funko...
ahora toy haciendo otra funcion pero me
newImage = System.Drawing.Image.FormStream(stream) se cae diciendo Parameter no valid

adjunto codigo...

Código:
 protected void Page_Load(object sender, EventArgs e)
    {
            string sql = string.Format("SELECT TOP 1 ItemId,Thumb FROM RubrikkImg.dbo.Attachment");
            List<object[]> img = Db.GetData(sql);
            lblResult.Text = String.Format("ItemId is {0} - \n Thumb Data ", img[0][0].ToString());//,BitConverter.ToString((byte[])img[0][1]));
            // Display the image from the database

            byteArrayToImage((byte[])img[0][1]); //img[0][0].ToString();




    }

    private void byteArrayToImage(byte[] byteArrayIn)
    {
        System.Drawing.Image newImage;

        string strFileName = GetTempFolderName() + "yourfilename.gif";
        if (byteArrayIn != null)
        {
            using (MemoryStream stream = new MemoryStream(byteArrayIn))
            {
                newImage = System.Drawing.Image.FromStream(stream);

                newImage.Save(strFileName);

                Image1.Attributes.Add("src", strFileName);
            }

            lblResult.Text = "The image conversion was successful.";
        }
        else
        {
            Response.Write("No image data found!");
        }
    }

    private static string GetTempFolderName()
    {
        string strTempFolderName = @"C:\Test";

        if (Directory.Exists(strTempFolderName))
        {
            return strTempFolderName;
        }
        else
        {
            Directory.CreateDirectory(strTempFolderName);
            return strTempFolderName;
        }
    }
  #4 (permalink)  
Antiguo 06/05/2010, 08:24
Avatar de jahman  
Fecha de Ingreso: noviembre-2003
Ubicación: Oslo
Mensajes: 230
Antigüedad: 20 años, 5 meses
Puntos: 0
Respuesta: Mostrar imagen desde SQL C#

ola bueno sigo con el mismo problema solo q esta vez me di cuenta q no lo mostraba por inconcisitencia en el tipo de dato por ejemplo cuando recojo un fotos y lo convierto a byte[] me muestra con byte[4347] y funciona bien pero cuando recojo esa misma foto desde la base de datos campo tipo Image me devuelve byte[13]

como pueden ver la fotos se guardan mal en la bd...

default.aspx donde muestro o recojo la foto
el q esta en rojo es cuando cojo la foto desde el hdd
y el azul desde la bd
Código:
protected void Page_Load(object sender, EventArgs e)
    {
            string sql = string.Format("SELECT ItemId,Contents FROM RubrikkImg.dbo.Attachment Where ItemId = '12'");
            List<object[]> img = Db.GetData(sql);
            //lblResult.Text = String.Format("ItemId is {0} - \n Thumb Data ", img[0][0].ToString());//,BitConverter.ToString((byte[])img[0][1]));
            // Display the image from the database

            //byteArrayToImage((byte[])img[0][1]); //img[0][0].ToString();
            byte[] dataI = (byte[])img[0][1];
            byte[] data = File.ReadAllBytes(@"C:\Test\2010.jpg"); 
            //byteArrayToImage(data);
            Response.ContentType = "image/jpeg";
            Response.BinaryWrite(data);
    }
upfile.aspx
aca es donde subo la foto a la bd creo...en la query lo paso como tipo Image pero al guardar como q no se traspasa bien....
Código:
protected void btnSave_Click(object sender, EventArgs e)
    {
        DataConnection();
        cmd = new SqlCommand();
        cmd.CommandText = "Insert into RubrikkImg.dbo.Attachment (ItemId,Contents )values('12',cast('" + FileUpload1.FileBytes + "' as Image))";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        /*string strPath = Server.MapPath("C:\\Test\\");
        if (FileUpload1.HasFile)
        {
            FileUpload1.SaveAs(strPath + FileUpload1.FileName);
        }*/
        cmd.ExecuteNonQuery();

        Response.Write("File save successfully");
    }
espero q alguien me pueda orientar. Gracias
  #5 (permalink)  
Antiguo 03/01/2012, 07:12
Avatar de leo_nqn  
Fecha de Ingreso: abril-2010
Ubicación: Neuquen
Mensajes: 461
Antigüedad: 14 años
Puntos: 24
Respuesta: Mostrar imagen desde SQL C#

jahman .. solucionaste esto?
__________________

Blog: http://leonardonqn.blogspot.com
Twitter:@Leo_FFerreyra
  #6 (permalink)  
Antiguo 03/01/2012, 12:03
Avatar de AWesker  
Fecha de Ingreso: octubre-2008
Mensajes: 177
Antigüedad: 15 años, 6 meses
Puntos: 27
Respuesta: Mostrar imagen desde SQL C#

Interesante, pase por lo mismo hace tiempo, pero con la variante de que yo utilizaba LINQ. Te dejo el enlace por si te ayuda en algo:
http://www.forosdelweb.com/f29/asign...-image-745813/

Saludos...
  #7 (permalink)  
Antiguo 03/01/2012, 13:11
Avatar de jahman  
Fecha de Ingreso: noviembre-2003
Ubicación: Oslo
Mensajes: 230
Antigüedad: 20 años, 5 meses
Puntos: 0
Respuesta: Mostrar imagen desde SQL C#

Si hace tiempo q lo resolvi...
este era de mayo del 2010.

Etiquetas: sql, aspx
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 09:01.