Ler foto do banco de dados
16/09/2011
0
Alan Miranda
Posts
20/09/2011
Rodrigo Odasaki
20/09/2011
Alan Miranda
Eu já tenho as fotos com binarios e gostaria de mostrar alguns campos e uma foto em uma picturebox.
Camada DAL public SqlDataReader MostraUsuario(ClientesInformation cliente) { SqlConnection cn = new SqlConnection(); { cn.ConnectionString = Dados.StringDeConexao; SqlCommand cmd = new SqlCommand(); cmd.Connection = cn; cmd.CommandType = CommandType.Text; cmd.CommandText = "Select * from CLIENTES where CODIGO = @CODIGO"; cmd.Parameters.AddWithValue("@CODIGO", cliente.Codigo); cn.Open(); SqlDataReader Leitor; Leitor = cmd.ExecuteReader(); if (Leitor.Read()) { cliente.Nome = Leitor["NOME"].ToString(); cliente.Email = Leitor["EMAIL"].ToString(); cliente.Telefone = Leitor["TELEFONE"].ToString(); cliente.Photo = (byte[])(Leitor["PHOTO"]); } return Leitor; } } Camada UI, Nessa camada não sei se tenho que converter os bytes para jogar no picture box... ClientesInformation Cliente = new ClientesInformation(); Cliente.Codigo = Convert.ToInt32(TxtCodigo.Text); Cliente.Nome = TxtUsuario.Text; Cliente.Email = TxtEmail.Text; Cliente.Telefone = TxtTelefone.Text; Cliente.Photo = (Byte[])Image1.DataBind; CadastroUsuarioFotu dados = new CadastroUsuarioFotu(); dados.MostraUsuario(Cliente);
Poderia me ajudar!
26/09/2011
Paulo Freire
http://stackoverflow.com/questions/1668469/system-drawing-image-to-stream-c
http://stackoverflow.com/questions/1346519/streaming-byte-to-image-in-asp-net-c
http://support.microsoft.com/kb/317701
http://www.codeproject.com/KB/IP/ykw1.aspx
http://www.codeproject.com/KB/cs/PictureBoxImage.aspx
29/09/2011
Alan Miranda
No meu caso estou em uma aplicação asp.net então o objeto é só image e não picturebox...
por isso estou com muitas dúvidas...a maioria dos exemplos é WINDOWS
Me ajudem ai pessoal, o código fonte já esta no tópico!
Desculpe me o transtorno!!
30/09/2011
Rodrigo Odasaki
É o fórum oficial da Microsoft.
Na categoria você coloca .Net Development Geral
30/09/2011
Paulo Freire
1º - Cria uma pagina tipo ShowImage.aspx
2º - No code bihend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace CMSO_Militar
{
public partial class ShowImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string conStr = ConfigurationManager.ConnectionStrings["Conexao_2045"].ConnectionString;
string ID = Request.QueryString["ID"];
if (!string.IsNullOrEmpty(ID))
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT FOTO, TIPO_FOTO FROM TBL_OFICIAIS WHERE ID = @id", con))
{
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(ID));
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] imgByte = (byte[])dr["FOTO"];
Response.ContentType = dr["TIPO_FOTO"].ToString();
Response.BinaryWrite(imgByte);
}
}
}
}
}
}
}
no browse coloque assim: localhost/ShowImage.aspx?ID=1 --- para o código 1
30/09/2011
Paulo Freire
1º - Dê um Add Item no seu projeto, escolha Web, Generic Handler, e de um nome qualquer tipo Handler.ashx
2º - Digite isso no code bihend
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string conStr = ConfigurationManager.ConnectionStrings["Conexao_CMSO_1248777"].ConnectionString;
string ID = context.Request.QueryString["ID"];
if (!string.IsNullOrEmpty(ID))
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT FOTO, TIPO_FOTO FROM TBL_OFICIAIS WHERE ID = @id", con))
{
cmd.Parameters.AddWithValue("@id", Convert.ToInt32(ID));
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] imgByte = (byte[])dr["FOTO"];
context.Response.ContentType = dr["TIPO_FOTO"].ToString();
context.Response.BinaryWrite(imgByte);
}
}
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
Para monstra no objeto Image da sua pagina ASP.Net:
this.Image1.ImageUrl = ("http://www.cmse.eb.mil.br/cmsp/456/Handler.ashx?id=" + GridViewOficiaisAtiva.DataKeys[Convert.ToInt32(e.CommandArgument)].Values["ID"].ToString());
ou
this.Image1.ImageUrl = ("http://www.cmse.eb.mil.br/cmsp/456/Handler.ashx?id=" + Datareader["ID"].ToString;
qualquer coisa griata ai,
Paulo Freire
30/09/2011
Alan Miranda
Então paulo na hora de ele fazer fazer o sql no banco, eu acho que está certo...
O problema é que eu preciso na camada de UI, converter essa foto e mostrar no objeto image....
ClientesInformation Cliente = new ClientesInformation(); Cliente.Codigo = Convert.ToInt32(TxtCodigo.Text); Cliente.Nome = TxtUsuario.Text; Cliente.Email = TxtEmail.Text; Cliente.Telefone = TxtTelefone.Text; Cliente.Photo = (Byte[])Image1.DataBind; //Nessa hora que eu não sei como converter e jogar no objeto.... CadastroUsuarioFotu dados = new CadastroUsuarioFotu(); dados.MostraUsuario(Cliente); //Aqui mostra as informações no seus especificos objetos, depois que o DataReader leu as informações no banco... //Cliente = TxtCliente Email = TxtEmail Telefone = Txttelefone image1 = image1 TxtUsuario.Text = Cliente.Nome; TxtEmail.Text = Cliente.Email; TxtTelefone.Text = Cliente.Telefone; image = //aqui tebho que passar a foto convertida para o usuário veja a foto...
Pessoal muito obrigado pela compreensão!
30/09/2011
Paulo Freire
Image.ImageUrl = ("http://www.seusite.com.br/Handler.ashx?id=" + Cliente.Codigo;
03/10/2011
Alan Miranda
Só mais um pergunta, ali mesmo onde eu trato as variaveis na UI tem como converter com File Stream ou MemoryStrem ?
Obrigado Paulo!
04/10/2011
Paulo Freire
byte[] imgByte = (byte[])dr["FOTO"];
context.Response.BinaryWrite(imgByte);
07/10/2011
Alan Miranda
Consegui fazer agora, mas tenho um pergunta...Na vdd nós fazemos dois selects no banco certo ? Se tiver muita foto no banco não vai dar problema de perfomance ?
Por isso que estava querendo converter a foto aqui nessa camada UI, é possivel ou somente criando um Handler ?
ClientesInformation Cliente = new ClientesInformation(); Cliente.Codigo = Convert.ToInt32(TxtCodigo.Text); CadastroUsuarioFotu dados = new CadastroUsuarioFotu(); dados.MostraUsuario(Cliente); TxtUsuario.Text = Cliente.Nome; TxtEmail.Text = Cliente.Email; TxtTelefone.Text = Cliente.Telefone; Image1.imageUrl = URL;
Muito obrigado Mesmo!
Clique aqui para fazer login e interagir na Comunidade :)