C# 从sql数据库检索图像(字节数组)并显示图像
在我的wpf mvvm应用程序中,我编写了一个用于图像上传和保存到数据库的代码。 代码运行良好,图像保存到数据库中。 这里我需要从数据库中检索图像并显示在图像框中C# 从sql数据库检索图像(字节数组)并显示图像,c#,wpf,image,mvvm,C#,Wpf,Image,Mvvm,在我的wpf mvvm应用程序中,我编写了一个用于图像上传和保存到数据库的代码。 代码运行良好,图像保存到数据库中。 这里我需要从数据库中检索图像并显示在图像框中 public void Upload(object obj) { try { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.DefaultExt = ".png";
public void Upload(object obj)
{
try
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "Image files (*.png;*.jpg)|*.png;*.jpg";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
UploadText = filename;
FileStream FS = new FileStream(filename, FileMode.Open, FileAccess.Read);
byte[] img = new byte[FS.Length];
FS.Read(img, 0, Convert.ToInt32(FS.Length));
UploadLogo = img;
Stream reader = File.OpenRead(filename);
System.Drawing.Image photo = System.Drawing.Image.FromStream((Stream)reader);
MemoryStream finalStream = new MemoryStream();
photo.Save(finalStream, ImageFormat.Png);
// translate to image source
PngBitmapDecoder decoder = new PngBitmapDecoder(finalStream, BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
ClientLogo = decoder.Frames[0]; ;
}
}
catch (Exception ex)
{
throw ex;
}
}
public void上传(object obj)
{
尝试
{
Microsoft.Win32.OpenFileDialog dlg=新的Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt=“.png”;
dlg.Filter=“图像文件(*.png;*.jpg)|*.png;*.jpg”;
可为空的结果=dlg.ShowDialog();
如果(结果==真)
{
字符串文件名=dlg.filename;
UploadText=文件名;
FileStream FS=newfilestream(文件名,FileMode.Open,FileAccess.Read);
字节[]img=新字节[FS.Length];
FS.Read(img,0,Convert.ToInt32(FS.Length));
上传logo=img;
流读取器=File.OpenRead(文件名);
System.Drawing.Image photo=System.Drawing.Image.FromStream((流)读取器);
MemoryStream finalStream=新的MemoryStream();
保存(finalStream,ImageFormat.Png);
//翻译成图像源
PngBitmapDecoder解码器=新的PngBitmapDecoder(最终流,BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default);
ClientLogo=decoder.Frames[0];
}
}
捕获(例外情况除外)
{
掷骰子;
}
}
如何将此字节数据转换为图像
提前感谢使用下面的代码
object binaryData = ("select ImageDataColunm from table where id=yourID");// use your code to retrive image from database and store it into 'object' data type
byte[] bytes = (byte[])binaryData;
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
AspImageID.ImageUrl= "data:image/png;base64," + base64String;
编辑:您可以在几周前回答这个问题您好,我正在检查。但是它不起作用。。我在wpf中使用图像工具,所以它需要图像源。AspImageID.ImageUrl在我的代码上载徽标中是字符串,具有来自数据库的字节这是我的imagesource属性私有imagesource\u clientlogo;public ImageSource ClientLogo{get{return{U ClientLogo;}set{U ClientLogo=value;OnPropertyChanged(“ClientLogo”);}}@Arun-请查看更新的答案链接Anywhere know“data:image/png;base64,”是否在存储图像之前删除,并在读取图像时重新添加?