[英]Retrieving binary back to image and from database and save into a folder using WPF
我已成功将图像转换为二进制文件,并使用linq to sql WPF将其保存到数据库中,现在我想将其恢复为图像格式并将其保存到计算机中的特定文件夹中。
我读过许多博客和文章,这些文章和文章从数据库中检索图像二进制文件,然后将其显示在PictureBox中,我要做的就是选择图像并将其使用linq to sql保存到特定的文件夹中。
到目前为止我尝试过的用于上传图片的代码:
private void Browse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".jpg";
ofd.Filter = "Image File (.jpg) | *.jpg";
Nullable<bool> result = ofd.ShowDialog();
if(result == true)
{
string fileName = ofd.FileName;
_txtFileName.Text = fileName;
}
}
private void Upload_Click(object sender, RoutedEventArgs e)
{
using(ImageDataContext db=new ImageDataContext())
{
image_data img = new image_data();
img.image = ConverImageToBinary(_txtFileName.Text);
try
{
db.image_datas.InsertOnSubmit(img);
db.SubmitChanges();
MessageBox.Show("Picture Upload Successfully", "Success", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public static byte[] ConverImageToBinary(string convertedImage)
{
try
{
FileStream fs = new FileStream(convertedImage, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] image = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return image;
}
catch(Exception ex)
{
throw ex;//MessageBox.Show(ex.Message, "error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
读取图像的代码首先是复杂的方法,您将其作为Stream打开并很好地读取所有字节。 有一种方法可以做到这一点,因此您可以将整个ConverImageToBinary方法替换为
img.image = File.ReadAllBytes(_txtFileName.Text);
同样,您也绝不会将任何东西“转换”为任何东西,图像只是磁盘上的一个字节数组,您已经读取了它,并将其保存到数据库中,如果您将其读回并保存回去(使用这次File.WriteAllBytes)它会很好地工作,所以
如果要写入磁盘,则只需将映像保存回磁盘,如下所示:
File.WriteAllBytes(@"d:\myfile.bmp",img.Image.ToArray()) ;
并确保您更改扩展名以匹配您的文件类型(因此bmp表示位图jpg jpeg等等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.