简体   繁体   中英

How to display an image inside a imagebox that is stored inside a SQL Server database?

I have a bunch of images stored in a SQL Server database and I want to be able to display these images once the WPF application loads in. I have been doing a lot of research and the closest thing to solving this problem is the code I have found below but I'm not even sure if that is correct and it doesn't work so far.

Code:

public MainWindow()
{
        InitializeComponent();

        SqlConnection sqlConnection = new SqlConnection(@"Data Source=LAPTOP-3SCT3MQA\SQLEXPRESS;Initial Catalog=RareMantis;Integrated Security=True");

        SqlDataAdapter dataAdapter = new SqlDataAdapter(new SqlCommand("SELECT GameCover FROM tblGames WHERE GameID = 1", sqlConnection));
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);

        if (dataSet.Tables[0].Rows.Count == 1)
        {
            Byte[] data = new Byte[0];
            data = (Byte[])(dataSet.Tables[0].Rows[0]["GameCover"]);
            MemoryStream mem = new MemoryStream(data);            
            // GameCover1.Image = System.Drawing.Image.FromStream(mem); 
            //              ^ this word(Image) is causing an error 
        }
}
 <Image x:Name="GameCover1"  HorizontalAlignment="Left" Height="226" Margin="36,314,0,-1.6" VerticalAlignment="Top" Width="411"/>

The first error you mention:

'Image' does not contain a definition for 'Image'

occures because the WPF control Image does not have a property named "Image". Instead, you need to use the Source property.

MarcBernier was on the right track trying to convert the binary data from SQL into a usable image, but the method he provided is for Winforms, not WPF. Since the two aren't compatible you get the second error from the comments:

Cannot implicitly convert type 'System.Drawing.Image' to 'System.Windows.Media.ImageSource'

As it points out, you need an ImageSource object. After a bit of research, I came across another stackoverflow question with an answer that should also help you. Try this:

GameCover1.Image = BitmapFrame.Create(mem, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);

As a final note, pmbAustin is correct that you should no longer be using the SQL image type. This solution should still work after switching over to varbinary(MAX) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM