简体   繁体   中英

How to save an image into a database?

I am using WPF to insert an image to my MySQL database. I can upload the file to image control but I don't know how to save it.

Here is what I've done so far. The emp_image is the image control that displays the photo.

private void btn_save_image_click(object sender,...)   
{   
    Mysqlconnection cn= new mysqlconnection(connectionstring);    
    byte[] imagedata;    
    imagedata=File.ReadAllBytes(emp_img);  //..here is error,it says has invalid arguments..//
    mysqlcommand= new mysqlcommand("insert into dep_table(photo)values(?data)",cn);    
    cmd.parameters.addwithvalue("?data", imagedata);    
    cn.open();    
    cmd.executeNonQuery();    
    cn.close();
}

you need to convert the image source to byte[] :

public static byte[] ImageToArray(BitmapSource image)
{
    var encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(image));

    using (var stream = new MemoryStream())
    {
        encoder.Save(stream);
        return stream.ToArray();
    }
}

Then, call the function:

imagedata = ImageToArray((BitmapSource)emp_img.Source);

Seems you are not passing the file path.

Please check File::ReadAllBytes Method

Should be something like

var imagedata=File.ReadAllBytes(filepath);

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