我已成功将图像转换为二进制并使用 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);
}
}
首先读取图像的代码非常复杂,您将其作为流打开并很好地读取所有字节。有一个方法可以完全做到这一点,因此您可以将整个 ConverImageToBinary 方法替换为
img.image = File.ReadAllBytes(_txtFileName.Text);
另外,您从未将任何内容“转换”为任何内容,图像只是磁盘上的字节数组,您已经读取了它,将其保存到数据库中,如果您将其读回并保存回来(这次使用 File.WriteAllBytes)它会工作得很好,所以
如果您想写入磁盘,只需将图像保存回磁盘,如下所示:
File.WriteAllBytes(@"d:\myfile.bmp",img.Image.ToArray()) ;
并确保更改扩展名以匹配您的文件类型(例如 bmp 表示位图 jpeg 表示 jpeg 等)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)