- Back to Home »
- WPF »
- WPF Browse Image with OpenFileDialog and saving it in SQL Server database using C# ADO.NET Code
Posted by :
Sudhir Chekuri
Monday, 23 December 2013
SQL Query to create table in SQL Server database to save image selected from WPF application
CREATE TABLE [dbo].[saveimage](
[sno] [int] IDENTITY(1,1) NOT NULL,
[img] [varchar](max) NULL
)
XAML Code in WPF application containing browse button, image and Upload button
<Window x:Class="SaveImageInDb.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel VerticalAlignment="Center" >
<Button Name="BtnUBrowse" Height="50" Width="150" Click="BtnBrowse_Click" >Browse Image</Button>
<Border BorderBrush="Black" BorderThickness="1" Height="200" Width="150">
<Image Name="Img1" Height="200" Width="150" ></Image>
</Border><Button Name="BtnUploadImage" Height="50" Width="150" Click="BtnUploadImage_Click" >Upload Image</Button>
</StackPanel>
</Grid>
</Window>
C#.NET and ADO.NET Code to browse image using OpenFileDialog and uploading it after showing it in image control
using Microsoft.Win32;
using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace SaveImageInDb
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
Img1.Source = new BitmapImage(new Uri(op.FileName));
}
}
private void BtnUploadImage_Click(object sender, RoutedEventArgs e)
{
var imageBuffer = BitmapSourceToByteArray((BitmapSource)Img1.Source);
SqlConnection con = new SqlConnection("Data Source=SUDHIR;Initial Catalog=db_wpfimage;Integrated Security=True");
SqlCommand cmd = new SqlCommand("insert into saveimage values('" + imageBuffer + "')", con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{ MessageBox.Show("Image Uploaded to database"); }
}
private byte[] BitmapSourceToByteArray(BitmapSource image)
{
using (var stream = new MemoryStream())
{
var encoder = new PngBitmapEncoder(); // or some other encoder
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(stream);
return stream.ToArray();
}
}
}
}
how to dishplay this image in datagrid?
ReplyDeleteIt's Simple Using Data Adapter
Delete