Save image in directory without Savefiledialog

Asked

Viewed 3,339 times

0

I am developing a stock control application and in this application there is a product registration screen:

Tela de cadastro de produtos

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:

Tela de consulta de produtos

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?

  • 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.

  • Perfect, I get it now. I already set an example for you.

  • @jbueno The example?

  • Young man, sorry for the delay. There’s your example.

2 answers

3


As long as Picturebox contains a valid image, you can recover it using the property Image of the component and save it using the method Image.Save()

private void SalvarImagem()
{
    pictureBox1.Image.Save("D:\\teste.jpg", pictureBox1.Image.RawFormat);
}

Note that the second parameter of the method Save asks for a ImageFormat (image type - JPG, PNG, etc.), as this information already exists in the image it is possible to recover it without much effort using the property RawFormat.

Yes, that’s it! Of course you’ll need to do something to put the extension in the file name, but that’s just a small detail.


To find a particular file in a specific directory, you must use Directory.GetFiles(). I created a small example for you, obviously you have to adapt to your needs, but the basis is this.

public Image buscarImagemProduto(string pastaPadrao, string nomeUnicoArquivo)
{
    string[] arquivos = Directory.GetFiles(pastaPadrao, nomeUnicoArquivo);

    if(arquivos.Length > 1)
        MaisDeUmArquivoEncontrado();
    else if (arquivos.Length == 0)
        NenhumArquivoEncontrado();
    else
        return Image.FromFile(arquivo[0]);

    return null; // Qtd de arquivos é diferente de zero - adapte para suas necessidades
}
  • To recover the image when the user type the product name would look like? (The image is being saved with the product name provided in the product register)

  • You just want to know how to recover an image by name, right? From your comment it seems like you want me to create the whole rule for you...

  • Good guy, it’s not that, I just want to know how to recover too, it’s written up there, I need to know what code to use..

  • Quiet, young man. I just wanted to know if I had understood right what you meant. I didn’t say that’s what you want... =)

  • Sorry for the misinterpretation too! D I look forward to your so precious help!!

  • @Marlonleandro I adapted the answer. As soon as the delay, I’m running a little over the last few days.

Show 1 more comment

0

  • But When the user clicks on "Add photo" Opens a Filedialog and the image appears in the Picturebox of the registration screen, then would have to copy from Picturebox to a folder, this first code, has to inform the source, however it does not apply in my case

  • When you enter the image path that the user selected in Filedialog in the Picturebox Load method, this path is available in the Picturebox Imagelocation property. When you are saving, just use as source this property.

  • Can you give me an example, please?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.