首页 > 解决方案 > WPF - 使用 C# 从 WPF 中的 Mysql 数据库中检索(选择或下载)图像

问题描述

我可以通过这段代码在 C# 中的 WPF 中从 Mysql 数据库下载(检索)图像。我从这个https://www.experts-exchange.com/questions/25096053/Retrieve-images-in-C-WPF-Application-from-SQL-Server-Database.html 网站复制了这段代码。但我不知道这段代码是如何逐行工作的。如果有人知道这方面的知识,请提供帮助。

代码在这里。

string query = "SELECT image_data from image_table WHERE image_id=22";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader dataReader = cmd.ExecuteReader();
            while (dataReader.Read())
            {
                Byte[] bindata = (Byte[])dataReader["image_data"];
                MemoryStream strm = new MemoryStream();
                strm.Write(bindata, 0, bindata.Length);
                strm.Position = 0;
                System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                ms.Seek(0, SeekOrigin.Begin);
                bi.StreamSource = ms;
                bi.EndInit();
                download.Source = bi; 
            }

标签: c#mysqldatabasewpfimage

解决方案


我可以使用此代码在 c# 中的 wpf 中从数据库中检索图像。这段代码的唯一问题是它一次只能检索一个图像。在使用此代码之前添加 System.Drawing.Imaging。代码中的库。

BitmapImage bi = new BitmapImage();
                    System.Drawing.Image img;
                    MemoryStream strm = new MemoryStream();
                    strm.Write(bindata, 0, bindata.Length);
                    strm.Position = 0;
                    img = System.Drawing.Image.FromStream(strm);
                    bi.BeginInit();
                    MemoryStream ms = new MemoryStream();
                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    ms.Seek(0, SeekOrigin.Begin);
                    bi.StreamSource = ms; 
                    bi.EndInit();

推荐阅读