Save image and rename without SQL

Asked

Viewed 59 times

2

I’m having trouble saving several images without using a database. I have saved text data in txt, but cannot save images. I have already read the images.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void label1_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {
            pastaLabel.Text = folderBrowserDialog1.SelectedPath;
            string[] arquivos = Directory.GetFiles(pastaLabel.Text, "*.jpg");

            foreach (var arquivo in arquivos)
            {
                ImagensListBox.Items.Add(arquivo);
            }
        }
    }

    string arquivo;
    private void ImagensListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        arquivo = ImagensListBox.SelectedItem.ToString();
        imagemPictureBox.ImageLocation = arquivo;
    }

    private void salvarButton_Click(object sender, EventArgs e)
    { 
        ? ? ?
    }
  • Want to save image in txt?

1 answer

0

You can use the method below to convert the imagens in string of base64.

private string ImageToBase64(string imagePath)
{
    using (Image image = Image.FromFile(imagePath))
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }
}

And to convert the string base64 for imagem again:

private Image Base64ToImage(string base64)
{
    var bytes = Convert.FromBase64String(base64);
    Image image = null;
    using (var stream= new MemoryStream(bytes))
    {
        image = Image.FromStream(stream);

    }

    return image;

}

Browser other questions tagged

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