如何通过对话框上传图片到SQLite并输出到XAML,简化代码不拆分子节数组
问题修复与实现方案
1 存储失败问题修复
现有代码插入图片失败的核心原因是缺少两个关键执行步骤:
- 未打开数据库连接
- 未执行SQL插入命令
仅构造命令对象就弹出成功提示,实际没有任何数据写入数据库。
2 简化代码逻辑方案
SQLite存储二进制图片依赖BLOB类型,对应C#中的byte[]是底层必须的格式,但可以大幅简化读写阶段的冗余代码,无需手动操作文件流、二进制读取器等对象:
2.1 优化后的上传代码
private void Button_Foto_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp"; // 限制可选文件类型,避免无效文件上传 if (openFile.ShowDialog() != true) return; string imgPath = openFile.FileName; textBoxImg.Text = imgPath; // 一行代码读取图片字节数组,替代原有的流操作冗余代码 byte[] imageBytes = File.ReadAllBytes(imgPath); string imgFormat = Path.GetExtension(imgPath).TrimStart('.').ToLower(); string imgName = Path.GetFileNameWithoutExtension(imgPath); // 数据库写入逻辑 using (SQLiteConnection Connect = new SQLiteConnection($"Data Source={dbPath};Version=3;")) { Connect.Open(); // 必须显式打开数据库连接 string commandText = $"INSERT INTO {db.AppStaffs} ([image], [image_format], [image_name]) VALUES(@image, @format, @name)"; SQLiteCommand Command = new SQLiteCommand(commandText, Connect); Command.Parameters.AddWithValue("@image", imageBytes); Command.Parameters.AddWithValue("@format", imgFormat); Command.Parameters.AddWithValue("@name", imgName); Command.ExecuteNonQuery(); // 必须执行插入命令才会写入数据 MessageBox.Show("Изображение добавлено в базу данных"); } }
2.2 从数据库读取图片绑定到XAML
XAML中定义Image控件:
<Image x:Name="DisplayImage" Width="200" Height="200"/>
读取数据库中字节数组并绑定的逻辑:
// 从数据库查询得到imageBytes后,直接转成BitmapImage绑定 using (SQLiteConnection Connect = new SQLiteConnection($"Data Source={dbPath};Version=3;")) { Connect.Open(); string queryText = $"SELECT [image] FROM {db.AppStaffs} WHERE [image_name] = @targetName"; SQLiteCommand queryCmd = new SQLiteCommand(queryText, Connect); queryCmd.Parameters.AddWithValue("@targetName", "你需要查询的图片名称"); byte[] imageBytes = (byte[])queryCmd.ExecuteScalar(); if(imageBytes != null) { using (MemoryStream ms = new MemoryStream(imageBytes)) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = ms; bitmap.EndInit(); DisplayImage.Source = bitmap; } } }
内容的提问来源于stack exchange,提问作者Edward Kamalov
相关产品推荐
相关产品推荐

