Gravar e ler imagens no SQL Server usando C#
Problema do aluno: Trabalho com Visual Studio 2005 (C# usando ADO.Net) e preciso criar uma rotina que leia e escreva imagens no SQL Server. Como faço?
Solução: Executamos o seguinte script no SQL Server Management Studio, para criar o banco e a tabela que armazenará as imagens:
CREATE DATABASE IMAGEM
GO
USE IMAGEM
–
CREATE TABLE IMAGENS
(
NOME VARCHAR(100) PRIMARY KEY,
BINARIO IMAGE NULL
)
Depois, abrimos o Visual Studio e criamos um Windows Application chamado ExemploImagem.
Depois, arrastamos para o form os controles Button, ComboBox, PictureBox, e Button e acertamos o layout.
Na janela de código, crie os métodos abaixo:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//
namespace ExemploImagem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//
private void button2_Click(object sender, EventArgs e)
{
comboBox1.Visible = false;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = “IMAGENS|*.jpg”;
if (ofd.ShowDialog() == DialogResult.OK)
{
string nomeDaImagem = “”;
long tamanhoDaImagem = 0;
byte[] imagemEmBytes = null;
nomeDaImagem = ofd.FileName;
FileInfo imagem = new FileInfo(nomeDaImagem);
tamanhoDaImagem = imagem.Length;
imagemEmBytes = new byte[Convert.ToInt32(tamanhoDaImagem)];
FileStream fs = new FileStream(nomeDaImagem, FileMode.Open, FileAccess.Read, FileShare.Read);
fs.Read(imagemEmBytes, 0, Convert.ToInt32(tamanhoDaImagem));
fs.Close();
pictureBox1.Image = Image.FromFile(nomeDaImagem);
SqlConnection c = null;
try
{
c = new SqlConnection(“Data Source=NOTEBOOK;Initial Catalog=IMAGEM;Integrated Security=True;Pooling=False”);
c.Open();
SqlCommand k = new SqlCommand(“INSERT INTO IMAGENS VALUES (@NOME, @BINARIO)”, c);
k.Parameters.Add(“@NOME”, SqlDbType.VarChar, 50);
k.Parameters.Add(“@BINARIO”, SqlDbType.Image);
k.Parameters[“@NOME”].Value = nomeDaImagem.Substring(nomeDaImagem.LastIndexOf(‘\\’) + 1).ToLower();
k.Parameters[“@BINARIO”].Value = imagemEmBytes;
MessageBox.Show(k.ExecuteNonQuery().ToString() == “1? ? “Gravei a bagaça” : “Ops… deu caca!!!”);
}
catch (SqlException s)
{
MessageBox.Show(“deu erro gravando a imagem\n\n” + s.Message);
}
finally
{
c.Close();
}
}
}
//
private void button1_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection(“Data Source=NOTEBOOK;Initial Catalog=IMAGEM;Integrated Security=True;Pooling=False”);
SqlDataAdapter da = new SqlDataAdapter(“SELECT ‘(escolha uma opção)’ UNION SELECT NOME FROM IMAGENS”, c);
DataSet ds = new DataSet();
da.Fill(ds);
comboBox1.Visible = true;
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
//
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Visible = false;
}
//
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > 0)
{
SqlConnection c = new SqlConnection(“Data Source=NOTEBOOK;Initial Catalog=IMAGEM;Integrated Security=True;Pooling=False”);
c.Open();
SqlCommand k = new SqlCommand(“SELECT BINARIO FROM IMAGENS WHERE NOME = @NOME”, c);
k.Parameters.Add(“@NOME”, SqlDbType.VarChar, 50);
k.Parameters[“@NOME”].Value = comboBox1.Text;
byte[] imagemEmBytes = (byte[])k.ExecuteScalar();
MemoryStream ms = new MemoryStream();
ms.Write(imagemEmBytes, 0, imagemEmBytes.Length);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
}