我正在尝试从WPF中的 .mdb 数据库加载图片。我使用此代码:
public void loadimg()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from recents", con);
DataTable table = new DataTable;
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
adap.Fill(table);
if (table.Rows.Count <= 0)
{
MsgBox("nooo");
}
else
{
MemoryStream stream = new MemoryStream();
StreamWriter stm;
BinaryWriter writer = new BinaryWriter(stream);
int bufferSize = 100;
byte[] outByte = new byte[bufferSize + 1];
long retval;
long startIndex = 0;
string pubID = "";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
reader.Read();
while (reader.Read())
{
startIndex = 0;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
startIndex += bufferSize;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
}
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
}
reader.Close();
con.Close();
stream.Position = 0;
stream.Seek(0, SeekOrigin.Begin);
System.Drawing.Image _Image = System.Drawing.Image.FromStream(stream);
image1.Source = System.Windows.Media.Imaging.BitmapFrame.Create(stream);
}
}
上面的代码返回错误:
没有找到适合完成此操作的成像组件。
我花了好几个小时试图弄清楚如何修复它。任何帮助都会受到高度赞赏。
更新 在评论中,我被问到是否正确插入数据..好吧,这里是我用来插入数据的代码:
public void adddata()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert into recents(Pic)values(@pic)", con);
byte[] data;
System.Drawing.Image myimage = System.Drawing.Image.FromFile("E:\\19686468_1419770068104721_1127495277_o.png");
using (MemoryStream ms = new MemoryStream())
{
myimage.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
data = ms.ToArray();
}
cmd.Parameters.AddWithValue("@pic", data);
cmd.ExecuteNonQuery();
con.Close();
}
请帮帮我!
答案 0 :(得分:-2)
修正了......对于将来遇到此错误的任何人:
2。您不需要做一些繁重的编码就可以将图像转换为字节!
最后,让我们编码:
public void loadimg()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from recents", con);
OleDbDataReader _dr;
_dr = cmd.ExecuteReader;
byte[] _photo;
while (_dr.Read())
{
try
{
_photo = (byte[])_dr(1);
BitmapImage bi = new BitmapImage();
using (MemoryStream strm = new MemoryStream(_photo))
{
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = strm;
bi.EndInit();
}
image1.Source = bi;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}