Click here to Skip to main content
15,898,947 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to use this code in a save button for inserting image as a string in a text data type in sql server using c# winforms. The code below converts an image to string but I don't know how to use it in saving/inserting. Any help will be appreciated. Thank you!

What I have tried:

C#
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;
  }
}
Posted
Updated 30-Aug-17 3:26am
v2
Comments
Jochen Arndt 30-Aug-17 9:32am    
Just store it in the database as any other string. How to do that depends on the database interface used by your application.

However, with binary data it is common to store them as BLOB (Binary Large OBject) instead of base64 encoded strings which increases the storage size.

With very large and/or many images it is even common to store the images as they are on disk and have only the file name in the database.

Don't store images in Base64 in your DB - it's very inefficient and images are big enough to start with that it's often a bad idea to store them at all. Small numbers of Thumbnails (or thumb sized images) OK - but full sized images or large quantities and you start to slow everything down dramatically. A better idea is to store them in binary using a BLOB / IMAGE / VARBINARY column, or even better store a path to the file in the DB, and access the image that from that as necessary.

Inserting binary data is simple - provided you use parameterized queries which should always do anyway - you'll find the code here: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^]
 
Share this answer
 
Comments
CPallini 30-Aug-17 11:38am    
5.
 
Share this answer
 
Comments
OriginalGriff 30-Aug-17 10:33am    
Downvote countered.
CPallini 30-Aug-17 11:37am    
Thank you, Griff! :-)

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