0
I am developing a stock control application and in this application there is a product registration screen:
The images of the products are being saved in the Mysql database. I received some tips and among them was that it is not recommended to save images in the database, even because the field of product search on the query screen was too slow, because the image is converted to byte as follows:
public void CarregaImagem(String imgCaminho)
{
try
{
if (string.IsNullOrEmpty(imgCaminho))
return;
//fornece propriedadese métodos de instância para criar, copiar,
//excluir, mover, e abrir arquivos, e ajuda na criação de objetos FileStream
FileInfo arqImagem = new FileInfo(imgCaminho);
//Expõe um Stream ao redor de um arquivo de suporte
//síncrono e assíncrono operações de leitura e gravar.
FileStream fs = new FileStream(imgCaminho, FileMode.Open, FileAccess.Read, FileShare.Read);
//aloca memória para o vetor
this.ProFoto = new byte[Convert.ToInt32(arqImagem.Length)];
//Lê um bloco de bytes do fluxo e grava osdados em um buffer fornecido.
int iBytesRead = fs.Read(this.ProFoto, 0, Convert.ToInt32(arqImagem.Length));
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
And saved on the seat as follows:
public void Incluir(ModeloProduto obj)
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conexao.ObjetoConexao;
cmd.CommandText = "insert into Produto (pro_foto) " +
"values (@foto); select @@IDENTITY;";
cmd.Parameters.Add("@foto", MySqlDbType.LongBlob);
if (obj.ProFoto == null)
{
//cmd.Parameters.AddWithValue("@pro_foto", DBNull.Value);
cmd.Parameters["@foto"].Value = DBNull.Value;
}
else
{
//cmd.Parameters.AddWithValue("@pro_foto", obj.pro_foto);
cmd.Parameters["@foto"].Value = obj.ProFoto;
}
}
On the query screen, the image is passed from the database to Picturebox when the user enters the product’s name or barcode. But I’d like to change that. Instead of saving the image in the database, when the user registers a product and clicks to save, the image is automatically passed from the Picturebox of the registration screen, to a directory inside the program folder and when doing a search on the query screen, the image to be recovered from the directory for Picturebox. The image also be saved with the product code number at the time of registration.
"Add Photo" button from the registration screen:
private void btLoFoto_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog od = new OpenFileDialog();
od.ShowDialog();
if (!string.IsNullOrEmpty(od.FileName))
{
this.foto = od.FileName;
pbFoto.Load(this.foto);
}
}
catch
{
MessageBox.Show("Algum erro ocorreu! Você pode estar tentando enviar outros tipos de arquivos \n"
+ "que não são imagens, selecione arquivos do tipo .png, .jpg, .bitmap, por exemplo.", "Erro");
}
}
Product consultation screen:
Code to recover bank image:
try
{
MemoryStream ms = new MemoryStream(modelo.ProFoto);
pbFoto.Image = Image.FromStream(ms);
this.foto = "Foto Original";
}
catch { }
Class Modeloproduct:
public ModeloProduto(String pro_foto)
{
this.CarregaImagem(pro_foto);
}
public ModeloProduto(byte[] pro_foto)
{
this.ProFoto = pro_foto;
}
private byte[] _pro_foto;
public byte[] ProFoto
{
get { return this._pro_foto; }
set { this._pro_foto = value; }
}
public void CarregaImagem(String imgCaminho)
{
try
{
if (string.IsNullOrEmpty(imgCaminho))
return;
//fornece propriedadese métodos de instância para criar, copiar,
//excluir, mover, e abrir arquivos, e ajuda na criação de objetos FileStream
FileInfo arqImagem = new FileInfo(imgCaminho);
//Expõe um Stream ao redor de um arquivo de suporte
//síncrono e assíncrono operações de leitura e gravar.
FileStream fs = new FileStream(imgCaminho, FileMode.Open, FileAccess.Read, FileShare.Read);
//aloca memória para o vetor
this.ProFoto = new byte[Convert.ToInt32(arqImagem.Length)];
//Lê um bloco de bytes do fluxo e grava osdados em um buffer fornecido.
int iBytesRead = fs.Read(this.ProFoto, 0, Convert.ToInt32(arqImagem.Length));
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
You already have the image in a picturebox and want to save it locally, right? But will this picture come from the picturebox? From the database? You’ll need to validate whether the image came from the bank or not?
– Jéf Bueno
The part of the database I want to delete, I just showed how the process takes place. The user in this case, uploads the image from somewhere on the computer to Picturebox, and wanted this image to be saved in a pre-defined folder on the computer, and to be loaded into the picturebox when the user did a product search.
– Marlon Pereira
Perfect, I get it now. I already set an example for you.
– Jéf Bueno
@jbueno The example?
– Marlon Pereira
Young man, sorry for the delay. There’s your example.
– Jéf Bueno