Salvar imagens com campos nulos

.NET

06/09/2013

Ola tem uma aplicação onde salvo imagens. Primeiro converto em bytes e depois retorno convertendo novamente para visualizar. Consigo salvar, mais quando tenho campos com imagens vazias nao consigo.

public Form1()
{
InitializeComponent();

//cria uma instãncia do objeto SqlConnection e data source
conexaoSQLServer = new SqlConnection(ConfigurationManager.ConnectionStrings["ImagensTeste.Properties.Settings.fotosConnectionString"].ConnectionString);
//obtem os dados da tabela imagens
getImagensSQLServer(conexaoSQLServer);
}

private SqlConnection conexaoSQLServer;

public void showData()
{
con.Open();
adp.Fill(ds);
txtId.Text = ds.Tables[0].Rows[position][0].ToString();
txtDescricao.Text = ds.Tables[0].Rows[position][1].ToString();

Image Image1 = null;
Image Image2 = null;
using (SqlConnection Conexao = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fotos.mdf;Integrated Security=True;Connect Timeout=30"))
{
Conexao.Open();
using (SqlCommand Comando = Conexao.CreateCommand())
{
Comando.CommandType = CommandType.Text;
Comando.CommandText = "SELECT * FROM TbFoto WHERE id=@Id";
Comando.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(txtId.Text);
using (SqlDataReader Reader = Comando.ExecuteReader())
{
if (Reader.HasRows)
{
Reader.Read();
Image1 = ConvertByteArrayToImage((Reader["foto"] as byte[]));
Image2 = ConvertByteArrayToImage((Reader["foto1"] as byte[]));
}
}
}
Conexao.Close();
}
if (Image1 != null)
{
picBrasao.Image = Image1;
picBrasao.Refresh();
picBrasao.Update();
}
if (Image2 != null)
{
picLogo.Image = Image2;
picLogo.Refresh();
picLogo.Update();
}

Conexao.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
showData();
}
void getImagensSQLServer(SqlConnection conexaoSQLServer)
{
try
{
//Inicializar o SQL adapter.
SqlDataAdapter ADAP = new SqlDataAdapter("Select id,descricao,foto,foto1 from tbFoto", conexaoSQLServer);

//Inicializa o Dataset.
DataSet DS = new DataSet();

//Preenche o dataset com a tabela Imagens
ADAP.Fill(DS, "foto");

//preenche o datagridviewe com o dataset.
dgvFotos.DataSource = DS.Tables["foto"];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnGravar_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtCaminho1.Text))
{
if (new FileInfo(txtCaminho1.Text).Exists)
{
if (!String.IsNullOrEmpty(txtCaminho2.Text))
{
if (new FileInfo(txtCaminho2.Text).Exists)
{
Image Image1 = Image.FromFile(txtCaminho1.Text);
Image Image2 = Image.FromFile(txtCaminho2.Text);
using (SqlConnection Conexao = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fotos.mdf;Integrated Security=True;Connect Timeout=30"))
{
Conexao.Open();
using (SqlCommand Comando = Conexao.CreateCommand())
{
Comando.CommandType = CommandType.Text;
Comando.CommandText = "INSERT INTO tbFoto (descricao,foto,foto1) values(@descricao,@foto,@foto1);";
Comando.Parameters.Add("@descricao", System.Data.SqlDbType.VarChar, 50).Value = this.txtDescricao.Text;
Comando.Parameters.Add("@foto", SqlDbType.Image).Value = ConvertImageToByteArray(Image1, ImageFormat.Jpeg);
Comando.Parameters.Add("@foto1", SqlDbType.Image).Value = ConvertImageToByteArray(Image2, ImageFormat.Jpeg);
if (Comando.ExecuteNonQuery() > 0)
{
MessageBox.Show("Imagem gravada com êxito", "Imagem: Ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Conexao.Close();
getImagensSQLServer(conexaoSQLServer);
LimparCampo();
}
}
else
{
MessageBox.Show("Imagem inválida", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

public byte[] ConvertImageToByteArray(Image image, ImageFormat imageFormat)
{
if (image == null)
return null;
MemoryStream ms = new MemoryStream();
image.Save(ms, imageFormat);
return ms.ToArray();
}

public Image ConvertByteArrayToImage(byte[] byteArray)
{
if (byteArray == null || byteArray.Length == 0)
{ return (null); }
return (Image.FromStream(new MemoryStream(byteArray)));
}

private void btnProcurarImagen1_Click(object sender, EventArgs e)
{
openBrasao.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openBrasao.ShowDialog();

if (res == DialogResult.OK)
{
txtCaminho1.Text = openBrasao.FileName;
picBrasao.Image = Image.FromFile(openBrasao.FileName);
}
}

private void btnProcurarImagen2_Click(object sender, EventArgs e)
{
openLogo.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*";
DialogResult res = openLogo.ShowDialog();

if (res == DialogResult.OK)
{
txtCaminho2.Text = openLogo.FileName;
picLogo.Image = Image.FromFile(openLogo.FileName);
}
}
private void btnRetonar_Click(object sender, EventArgs e)
{
Image Image1 = null;
Image Image2 = null;
using (SqlConnection Conexao = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fotos.mdf;Integrated Security=True;Connect Timeout=30"))
{
Conexao.Open();
using (SqlCommand Comando = Conexao.CreateCommand())
{
Comando.CommandType = CommandType.Text;
Comando.CommandText = "SELECT * FROM TbFoto WHERE id=@Id";
Comando.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(txtId.Text);
using (SqlDataReader Reader = Comando.ExecuteReader())
{
if (Reader.HasRows)
{
Reader.Read();
Image1 = ConvertByteArrayToImage((Reader["foto"] as byte[]));
Image2 = ConvertByteArrayToImage((Reader["foto1"] as byte[]));
}
}
}
Conexao.Close();
}
if (Image1 != null)
{
picBrasao.Image = Image1;
picBrasao.Refresh();
picBrasao.Update();
}
if (Image2 != null)
{
picLogo.Image = Image2;
picLogo.Refresh();
picLogo.Update();
}
}
Aguardo
Sigrids Lima

Sigrids Lima

Curtidas 0

Respostas

Joel Rodrigues

Joel Rodrigues

06/09/2013

Mas não consegue porque? Dá erro ao acessar um objeto nulo?
Se for, verifique se o campo está preenchido antes de tentar convertê-lo para imagem.
GOSTEI 0
Sigrids Lima

Sigrids Lima

06/09/2013

Quando coloco informaçoes na textbox e no picturebox consigo salvar normalmente, mas quando deixo o campo picturebox vazio nao consigo salvar nem apresenta erro.
GOSTEI 0
Sigrids Lima

Sigrids Lima

06/09/2013

Conseguir resolver o problema assim

private void btnGravar_Click(object sender, EventArgs e)
{
if ((picBrasao.Image != null) && (picLogo.Image != null))
{
using (SqlConnection Conexao = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fotos.mdf;Integrated Security=True;Connect Timeout=30"))
{
Conexao.Open();
using (SqlCommand Comando = Conexao.CreateCommand())
{
Comando.CommandType = CommandType.Text;
Comando.CommandText = "INSERT INTO tbFoto (descricao,foto,foto1) values(@descricao,@foto,@foto1);";
Comando.Parameters.Add("@descricao", System.Data.SqlDbType.VarChar, 50).Value = this.txtDescricao.Text;
Comando.Parameters.AddWithValue("@foto", SqlDbType.Image).Value = ConvertImageToByteArray(picBrasao.Image, ImageFormat.Jpeg);
Comando.Parameters.AddWithValue("@foto1", SqlDbType.Image).Value = ConvertImageToByteArray(picLogo.Image, ImageFormat.Jpeg);
if (Comando.ExecuteNonQuery() > 0)
{
MessageBox.Show("Imagem gravada com êxito", "Imagem: Ok", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Conexao.Close();
getImagensSQLServer(conexaoSQLServer);
LimparCampo();
}
}
else
{
MessageBox.Show("Erro na gravação", "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Obrigado
GOSTEI 0
Joel Rodrigues

Joel Rodrigues

06/09/2013

Obrigado por compartilhar a solução.
Tópico concluído.
GOSTEI 0
POSTAR