Click here to Skip to main content
15,917,320 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
using the code from 88388132 - @User-9325517 , how to display the image back to picture box using data grid view's event - cell click?

C#
 SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=notitest;user id=sa;password=cos123");
  cn.Open();
  SqlCommand cmd = new SqlCommand("insert imgtest values(" + textBox1.Text + ",'" + ImageToBase64(pictureBox1.Image,
System.Drawing.Imaging.ImageFormat.Png) + "')", cn);
  SqlDataReader dr = cmd.ExecuteReader();
  cn.Close();


//Retrive
SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=notitest;user id=sa;password=cos123");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from imgtest", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    textBox2.Text = dr[0].ToString();
    pictureBox2.Image = Base64ToImage(dr[1].ToString());
}
cn.Close();



//Methods
Hide   Copy Code
public string ImageToBase64(Image image,
          System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();
 
                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
 
        public Image Base64ToImage(string base64String)
        {
            // Convert Base64 String to byte[]
            byte[] imageBytes = Convert.FromBase64String(base64String);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);
 
            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            return image;
        }


What I have tried:

Tried this but i got an error saying "invalid length for a base-64 char array or string". I am saving the string into text field/data type in sql server and changing it to nvarchar or any other data types isn't an option.
C#
SqlConnection cn = new SqlConnection("data source=localhost;initial catalog=notitest;user id=sa;password=cos123");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from imgtest", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
    textBox2.Text = dr[0].ToString();
    pictureBox2.Image = Base64ToImage(dr[1].ToString());
}
cn.Close();
Posted
Updated 21-Sep-17 23:40pm
v2
Comments
Richard MacCutchan 21-Sep-17 11:44am    
If this refers to a code project article then you should post your question in the forum at the end of the article.
aaaaaaaaaaa222 23-Sep-17 8:21am    
that article's comment section isn't responsive anymore. It was dated years back, and I don't think I'll be able to receive answers from that comment section.
aaaaaaaaaaa222 23-Sep-17 8:23am    
I've been using parameterized queries ever since I started using sql with c# and I thank you for that cause your one of the reasons why I do. Continue helping others know what's the right thing to do. thank you for the reminder.
Richard Deeming 21-Sep-17 12:43pm    
Also, your application should NEVER connect as sa. That's an unrestricted user, which could be used to destroy your database, your server, or even your entire network.

Instead, create a user for your application which has only the permissions that your application requires, and use that instead.

And you should store your connection string in the configuration file, rather than hard-coding it:
How to get Connection String from App.Config in C#[^]

1 solution

At a guess, the data in your DB is not what you think it is: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] will explain why.

And as the others have said: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
Share this answer
 
Comments
aaaaaaaaaaa222 23-Sep-17 8:16am    
The codes above are from 88388132 - @User-9325517's article. I've read and saw a lot of your and other's comments helping others even before, so I do use parameterized queries. It just that the above code isn't parameterized by the creator. btw the link you commented helps. thankyou very much! :D
OriginalGriff 23-Sep-17 8:44am    
You're welcome!

But do yourself a favour: never copy code and run it without checking it first! A single unparameterized query, and your DB could go tits up ...

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