从Access DB将图片读入PictureBox [英] Read a picture from Access DB into PictureBox

查看:75
本文介绍了从Access DB将图片读入PictureBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图读取在C#Windows应用程序的PictureBox中作为OLE对象保存在Access DB中的图片.

I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application.

执行此操作的代码如下:

The code that does this is presented below:

        string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;";
        OleDbConnection oConn = new OleDbConnection(connString);
        oConn.Open();
        string commandString = "select * from employee where id = " + id + "";
        OleDbCommand oCmd = new OleDbCommand(commandString, oConn);
        OleDbDataReader oReader = oCmd.ExecuteReader(CommandBehavior.SequentialAccess);

        while (oReader.Read())
        {
            txtID.Text = ((int)oReader.GetValue(0)).ToString();
            txtName.Text = (string)oReader.GetValue(1);
            txtAge.Text = ((int)oReader.GetValue(2)).ToString();
            txtType.Text = (string)oReader.GetValue(3);
            byte[] imageBytes = (byte[])oReader.GetValue(4);

            MemoryStream ms = new MemoryStream();
            ms.Write(imageBytes, 0, imageBytes.Length);
            Bitmap bmp = new Bitmap(ms);
            pbPassport.Image = bmp;
        }

当我执行上面的代码时,在行上抛出参数无效"异常:

When I execute the above code, an 'Parameter is not valid' exception is thrown at the line:

Bitmap bmp = new Bitmap(ms)

从异常消息中可以明显看出,"ms"的格式不可识别.有什么建议可以克服这个问题吗?

From the exception message, it is clear that 'ms' is in a format that is not recognisable. Any suggestion to get past this?

推荐答案

您的字节流某种程度上已损坏,因为我尝试了您的确切方法,但用文件中的PNG数据填充了字节数组.

Your bytestream is corrupted somehow, becouse I tried the exact method of yours but filled the byte array with PNG data from a file instead.

我建议创建两个流,一个来自数据库,另一个来自作为数据库中图像源的文件.然后逐字节比较它们.如果甚至有一个字节的差异,则数据库图像数据将被破坏.

I would suggest creating two streams, one from the database, and one from the file that was the source of the image in the database. Then compare them byte by byte. If there is even one byte of diffrence, the database image data is corrupt.

这篇关于从Access DB将图片读入PictureBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆