Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

WPF Loading and Saving Image to SQL Database

$
0
0

Hi,

I'm trying to save a picture into a sql database as byte/image.  I think I got the loading of the picture but I can't seem to get the saving to work.  I'm using WPF binding with Entity Framework.

Here is my XAML:

<Button Grid.Row="0" Grid.Column="0" Name="tlb_AddPhoto" Click="tlb_AddPhoto_Click"><DockPanel><Image Source="/Resources/Images/New.png" Width="16" /><TextBlock HorizontalAlignment="Center" FontWeight="Bold">Add</TextBlock></DockPanel></Button><Image Grid.Row="0" Grid.Column="1" Name="img_Photo" Source="{Binding Path=Photo, Converter={StaticResource binaryImageConverter}}"></Image>

Here is my ImageConverter:

publicclass BinaryImageConverter : IValueConverter

 {

  publicobject Convert(object value, Type targetType, object parameter, CultureInfo culture)

  {

   if (value != null)

   {

    byte[] byteArray = value asbyte[];if (byteArray == null)returnnull;



    BitmapImage image = new BitmapImage();using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())

    {

     imageStream.Write(byteArray, 0, byteArray.Length);

     imageStream.Seek(0, System.IO.SeekOrigin.Begin);



     image.BeginInit();

     image.CacheOption = BitmapCacheOption.OnLoad;

     image.StreamSource = imageStream;

     image.EndInit();

     image.Freeze();

    }

    return image;

   }

   returnnull;

  }

  

  publicobject ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

  {

   thrownew NotSupportedException();

  }

 }

Here is my click add image button:

 

privatevoid tlb_AddPhoto_Click(object sender, RoutedEventArgs e)

  {
   Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
   dlg.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.* ";if (dlg.ShowDialog() == true)
   {
    System.IO.Stream stream = System.IO.File.Open(dlg.FileName, System.IO.FileMode.Open);

    BitmapImage imgsrc = new BitmapImage();
    imgsrc.BeginInit();
    imgsrc.StreamSource = stream;
    imgsrc.EndInit();this.img_Photo.Source = imgsrc;

   }

  }

 

I have textboxes on the same window that save back to the database fine through binding.  Can someone help me with what i'm doing wrong in the binding for the image?  How come the image does not save the source to the database?

Thank you in advance!


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>