简体   繁体   中英

Insert image into MS Access database using C#

I am trying to both image and name into my ms access database but I dont know how to do it. Currently, the first function I converted my input image to byte format. The seconds function is where I add my image into my database. Actually this code is from a tutorial, but they didnt tell on how to insert the image into the MS Access database. The comment of the codes have been explained clearly about the functions.

    private byte[] ConvertToDBFormat(Image InputImage)
    {
        Bitmap BmpImage = new Bitmap(InputImage);
        System.IO.MemoryStream Mystream = new System.IO.MemoryStream();
        BmpImage.Save(Mystream, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] ImageAsBytes = Mystream.ToArray();
        return ImageAsBytes;

    }
    /// <summary>
    /// Stores a Face image and its Name in the Training Set, in MS Access Database 
    /// </summary>
    /// <param name="ImageAsBytes"></param> Face image converted to bytes 
    /// <param name="FaceName"></param>the name of face set in the textbox
    private void AddFaceToDB(Image InputFace, string FaceName)
    {
        if (Connection.State.Equals(ConnectionState.Closed))
        {
            Connection.Open();
        }

        try
        {
            MessageBox.Show("Image saved at: " + rowNumber.ToString());
            OleDbCommand OledbInsert = new OleDbCommand("Insert INTO TrainingSet1 (FaceID, FaceName, FaceImage) VALUES('" + rowNumber.ToString() + "','" + txtBoxFaceName.Text + "',@MyImg)", Connection);
            OleDbParameter imageParameter = OledbInsert.Parameters.AddWithValue("@Img", SqlDbType.Binary);

        }

    }

Can someone help me to show me how to add image and text using C#. THis is my first time I am learning c# and MS Access database. Currently, I dont know how to continue with my code from here. The database part I am using OleDb. I really appreciate your helps. Thank you.

I hate to use an "answer" to give what might be more suitable as a comment, but I wanted to tell you two things.

First, if you want to store the images in the database, you should look at BLOBs (binary large objects).

But second and maybe more important, it seems the consensus on best practice is, if you can get away with it in your project, saving the image elsewhere and storing only the path in Access. This helps keep you under the Access db size cap and seems to keep the database more responsive as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM