如何将图像保存到数据库中?

时间:2015-09-21 08:50:47

标签: c# mysql wpf

我正在使用WPF将图像插入MySQL数据库。我可以将文件上传到图像控件,但我不知道如何保存它。

这是我到目前为止所做的。 emp_image是显示照片的图像控件。

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();
}

2 个答案:

答案 0 :(得分:1)

您需要将图像源转换为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();
    }
}

然后,调用函数:

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

答案 1 :(得分:-1)

好像你没有传递文件路径。

请检查File::ReadAllBytes Method

应该像

var imagedata=File.ReadAllBytes(filepath);
相关问题