Click here to Skip to main content
15,895,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everyone, how will I insert an image to MS Access database after I converted the image into byte[]?


I used this code to convert the image into byte[]
C#
public byte[] imageToByteArray(Image imageIn)
       {
           MemoryStream ms = new MemoryStream();
               imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

               byte[] yeah = ms.ToArray() ;
               return yeah;

       }


Thanks in advance. :)
Posted
Updated 28-Nov-15 19:08pm
v5

Like this one:
C#
var pic = File.ReadAllBytes(yourFileName);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 (id, picture) values (@p1, @p2)";
cmd.Parameters.AddWithValue("@p1", TextBox1.Text);
cmd.Parameters.AddWithValue("@p2", pic);
cmd.ExecuteNonQuery();

Here is an article on it:
Inserting images into MS Access file using OLEDB[^]
 
Share this answer
 
Comments
Jeff Garcia Samson 22-Mar-16 6:59am    
Thanks. :)
ridoy 24-Mar-16 13:21pm    
welcome.
C#
public static void AddEmployee(
  string lastName, 
  string firstName, 
  string title, 
  DateTime hireDate, 
  int reportsTo, 
  string photoFilePath, 
  string connectionString)
{
  byte[] photo = GetPhoto(photoFilePath);

  OleDbCommand command = new OleDbCommand(
    "INSERT INTO Employees (LastName, FirstName, " +
    "Title, HireDate, ReportsTo, Photo) " +
    "Values(@LastName, @FirstName, @Title, " +
    "@HireDate, @ReportsTo, @Photo)", connection); 

  command.Parameters.Add("@LastName",  
     SqlDbType.NVarChar, 20).Value = lastName;
  command.Parameters.Add("@FirstName", 
      SqlDbType.NVarChar, 10).Value = firstName;
  command.Parameters.Add("@Title",     
      SqlDbType.NVarChar, 30).Value = title;
  command.Parameters.Add("@HireDate", 
       SqlDbType.DateTime).Value = hireDate;
  command.Parameters.Add("@ReportsTo", 
      SqlDbType.Int).Value = reportsTo;

  command.Parameters.Add("@Photo",
      SqlDbType.Image, photo.Length).Value = photo;

  connection.Open();
  command.ExecuteNonQuery();
  }
}

public static byte[] GetPhoto(string filePath)
{
  FileStream stream = new FileStream(
      filePath, FileMode.Open, FileAccess.Read);
  BinaryReader reader = new BinaryReader(stream);

  byte[] photo = reader.ReadBytes((int)stream.Length);

  reader.Close();
  stream.Close();

  return photo;
}

From MSDN[^]

Refer this as well-
http://hubpages.com/technology/C-program-that-interfaces-with-MS-Access-Store-data-text-image-in-an-Access-database-file[^]

-KR
 
Share this answer
 
v2
Comments
Jeff Garcia Samson 22-Mar-16 6:59am    
Thanks Sir. :)

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