Click here to Skip to main content
14,243,279 members
Rate this:
Please Sign up or sign in to 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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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:
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:
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);
        }
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100