我有一个数据库,我有一个表产品,我在那里保留产品的图片, 在c#中 public byte []图片
在我的数据库中,它是varbinary类型(自动转换) 所以,我想要做的是在pictureBox1.Image中显示我的图像来自数据库;
var q_pic = from p in context.Products
where p.ID == value // Id of product that i want
select new
{
p.Picture
};
现在
picutreBox1.Image = ??
原因
pictureBox1.Image = q_pic doeasn't work
现在我有了这个
var bytes = from p in context.Products
where p.ID == value // Id of product that i want
select p.Picture;
if (bytes != null)
{
using (var ms = new MemoryStream(bytes))
{
using (var image = Image.FromStream(ms))
{
pictureBox1.Image = (Image)image.Clone();
}
}
}
得到这个
Error 1 The best overloaded method match for 'System.IO.MemoryStream.MemoryStream(byte[])' has some invalid arguments
Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable<byte[]>' to 'byte[]'
答案 0 :(得分:1)
你可能想要更像的东西:
var q_pic = from p in context.Products
where p.ID == value // Id of product that i want
select p.Picture;
// FirstOrDefault will return null if there were no matches
pictureBox1.Image = q_pic.FirstOrDefault();
您原来的主要问题是您使用的是匿名类型(不必要),并尝试分配给IEnumerable<T>
,而不仅仅是图片本身。从查询中删除new {...
可解决第一个问题,并使用FirstOrDefault
从T
中提取单个IEnumerable<T>
(第一个)。
鉴于您的评论,您的查询很明显会返回byte[]
,而不是图片。你需要把它写成:
var first = context.Products.FirstOrDefault(p => p.ID == value);
if (first != null)
{
using (var ms = new MemoryStream(first.Picture))
{
using(var image = Image.FromStream(ms))
{
pictureBox1.Image = (Image)image.Clone();
}
}
}
答案 1 :(得分:1)
Reed Copsey列出的内容将帮助您找到Product对象上的byte []。要将它放在PictureBox的Image属性中,您需要将字节数组转换为Image。
using (var ms = new System.IO.MemoryStream(q_pic)) {
using(var img = Image.FromStream(ms)) {
pictureBox1.Image = img;
}
}
答案 2 :(得分:0)
使用LINQ时,从数据库中获取“System.Data.Linq.Binary”类型。此类型具有ToArray()
方法,该方法返回byte[]
。你应该纠正你这样的代码:
var bytes = from p in context.Products
where p.ID == value // Id of product that i want
select p.Picture;
byte[] trueBytes = bytes.ToArray();
if (trueBytes != null)
{
using (var ms = new MemoryStream(trueBytes))
{
using (var image = Image.FromStream(ms))
{
pictureBox1.Image = (Image)image.Clone();
}
}
}
答案 3 :(得分:0)
只需制作
byte[] imgdata;
string id = dataGridViewX1.SelectedRows[0].Cells[0].Value.ToString();
var q = db.tbl_aezas.First(c => c.id == id);
imgdata = q.image.ToArray();
System.IO.MemoryStream ms = new System.IO.MemoryStream(imgdata);
pictureBox1.Image = Image.FromStream(ms);
答案 4 :(得分:0)
DataBonzClinicDataContext db = new DataBonzClinicDataContext();
var tsel = (from u in db.tblsysusers
where (u.pass_id==cbxUser.Text.ToString().Trim())
select u.pass_imgid).First();
if (tsel != null)
{
var imgdata = tsel.ToArray();
System.IO.MemoryStream ms = new System.IO.MemoryStream(imgdata);
pictureBox1.Image = Image.FromStream(ms);
}