从DB检索图像时参数无效

时间:2013-10-30 11:52:14

标签: c# image oledb ms-access-2010

最后,我想从Access数据库中获取一个OLE类型的图像并将其放入一个图片框中。在C#和MS Access 2010中使用Visual Studio 2012.我的解决方案是一个非Web相关的应用程序。

所以这是查询代码。我正在构建一个对象(Equipamento),其中包含System.Drawing.Image属性,这是该问题的焦点。

OleDbConnection l = OleDbConnectionDAO.createConnection();
Equipamento eq = new Equipamento();

try
{
    OleDbDataAdapter adapter = new OleDbDataAdapter(
        "SELECT * FROM [APP_Equipamento_Geral] WHERE COD_ETIQ like '%"
           + codigo
           + " %'",
        l);
    DataSet ds = new DataSet();
    adapter.Fill(ds, "[APP_Equipamento_Geral]");
    string s = ds.Tables["[APP_Equipamento_Geral]"].Columns[16].ColumnName;
    foreach (DataRow row in ds.Tables["[APP_Equipamento_Geral]"].Rows)
    {                
        eq.NInventario = row["Codigo"].ToString();
        eq.Modelo = row["MODELO"].ToString();
        eq.Marca = row["Marca_"].ToString();
        eq.GamaMedida = row["Gama Medida"].ToString();

        if (row["FOTO"] != DBNull.Value && row["FOTO"] != null)
        {
            byte[] b = new byte[0];
            b = (byte[])row["FOTO"];

            eq.Img = getImageFromBytes(b);//Error caught here
        } 


        //if (row["FOTO"] != DBNull.Value && row["FOTO"] != null)
        //{
        //    byte[] b = (byte[])row["FOTO"];
        //    MemoryStream ms = new MemoryStream(b);
        //    eq.Img = Image.FromStream(ms);  //Error caught here
        //} 
    }
}

这是辅助方法:

private Image getImageFromBytes(byte[] myByteArray)
{
    System.IO.MemoryStream newImageStream
        = new System.IO.MemoryStream(myByteArray, 0, myByteArray.Length);\

    return Image.FromStream(newImageStream, true);
}

最后评论的一段代码是我的另一个尝试,也给了

  

参数无效

错误。任何解决方案?

注意:如果我取出图像部分,一切正常。

2 个答案:

答案 0 :(得分:1)

存储为OLE object的图像与序列化System.Drawing.Image的格式不同。这就是我问图像是如何存储的原因。

虽然我无法保证这一点,但从未个人使用过,但我们建议使用以下代码。据推测,它使用MS的GDI + lib(包含在Win标准安装中)从/向Access OLE导入/导出图片。

http://www.access-im-unternehmen.de/index1.php?BeitragID=337&id=300

您可以在以下链接中找到其他建议(包括从Access中提取图像的实用程序):

Converting MS Access "OLE Objects" back to plain JPEGs - best way?

答案 1 :(得分:0)

您无法仅使用强制转换将图像或字符串转换为arraybite。

如果要将图像转换为arrayBite,请使用此函数

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

将arraybite重新转换为图像使用此

public Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    Image returnImage = Image.FromStream(ms);
    return returnImage;
}