Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello! I am now able to save and view Image from DB as a byte, now I need to convert it into string and I am receiving error. Any help or correction will be appreciated. Thank you.

What I have tried:

private void button1_Click(object sender, EventArgs e)
{
Image myImage = pictureBox1.Image;
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
data = ms.ToArray();
string s3 = Convert.ToBase64String(data);
data = Convert.FromBase64String(s3);
}



con.Open();
cmd = new SqlCommand("INSERT INTO kenny (id,picture) VALUES (@id,@IM)", con);
{
cmd.Parameters.AddWithValue("@IM", s3);
cmd.Parameters.AddWithValue("@id", textBox1.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
Posted
Updated 23-Sep-17 23:21pm
Comments
Richard MacCutchan 24-Sep-17 9:42am    
Why do you convert data to s3 and then immediately convert s3 to data? Decide which you need, a byte[] or a string. And also read OriginalGriff's suggestions closely.

1 solution

Please, do yourself a favour and review the C# basics: this is the third time I've seen that code this weekend, and what you are doing is making a fundamental mistake - then ignoring the error message you get.
s3 is a local variable in the button1_Click method:
C#
private void button1_Click(object sender, EventArgs e)
    {
    Image myImage = pictureBox1.Image;
    byte[] data;
    using (MemoryStream ms = new MemoryStream())
        {
        myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        data = ms.ToArray();
        string s3 = Convert.ToBase64String(data);
        data = Convert.FromBase64String(s3);
        }
And it's scope is restricted to the code block in which it is declared: the containing set of curly brackets.
As such, it doesn't exist outside your using block, and you get a compiler error.
Move the definition outside the using block, and it will compile:
C#
private void button1_Click(object sender, EventArgs e)
    {
    Image myImage = pictureBox1.Image;
    byte[] data;
    string s3;
    using (MemoryStream ms = new MemoryStream())
        {
        myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        data = ms.ToArray();
        s3 = Convert.ToBase64String(data);
        data = Convert.FromBase64String(s3);
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900