如何在扫描图像后将图像保存到数据库

时间:2013-10-08 05:43:35

标签: c#-4.0

我开发了一个扫描图像的Windows应用程序。扫描图像后,我想将它直接保存到数据库而不是本地机器...我使用的代码如下

try
{
    String str = string.Empty;
    WIA.CommonDialogClass scanner;
    ImageFile imageObject;

    scanner = new CommonDialogClass();
    imageObject = scanner.ShowAcquireImage
        (WiaDeviceType.ScannerDeviceType, 
        WiaImageIntent.ColorIntent,
        WiaImageBias.MinimizeSize,
        ImageFormat.Jpeg.Guid.ToString("B"), 
        false, 
        true,
        true);

    str = DateTime.Now.ToString();
    str = str.Replace("/", "");
    str = str.Replace(":", "");
    Directory.CreateDirectory("D:\\scanned1");
    //            MessageBox.Show(string.Format("File Extension = {0}\n
    //\nFormat = {1}", imageObject.FileExtension, imageObject.FormatID));
    imageObject.SaveFile(@"D:\scanned1\lel" + str + ".jpg");
    MessageBox.Show("Scanning Done");
}
catch (Exception ex)
{
    MessageBox.Show("Please check if the scanner is connected properly.");
}

而不是将其保存到D盘我想将它保存到数据库.....我该怎么做?PLZ回复......

1 个答案:

答案 0 :(得分:1)

我不知道“ImageFile”究竟是什么,但应该有一种方法将其转换为字节数组(byte [])。之后,您需要将该数组插入sql中的varbinary字段。 像这样的东西:

using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (@myvarbinaryvalue)", conn))
{
    cmd.Parameters.Add("@myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;
    cmd.ExecuteNonQuery();
}

ofc sqlcommand应该打开并且有效。 myarray的类型为byte []