Showing posts with label binary. Show all posts
Showing posts with label binary. Show all posts

Friday, 29 August 2014

Save image to database using C#

To convert this code to VB.net Click Here. Opens in new window.



Download project


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PictureToDatabase
{
public partial class ImageForm : Form
{
private readonly string connectionString = string.Empty;
private OleDbConnection connection;
private OleDbCommand command;
private List Images;

private MyImage currentImage;

///
/// Gets or sets the current image.
///
///
/// The current image.
///
private MyImage CurrentImage
{
get { return currentImage; }
set
{
currentImage = value;
if (currentImage != null)
{
PictureBox.Image = BinaryToImage(currentImage.FileData);
ImageNameLabel.Text = System.IO.Path.GetFileName(currentImage.FileName);
}
}
}

///
/// Initializes a new instance of the class.
///
public ImageForm()
{
InitializeComponent();
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ImageDatabase.accdb";
}

///
/// Browses the button click.
///
/// The sender.
/// The instance containing the event data.
private void BrowseButtonClick(object sender, EventArgs e)
{
var browseDialog = new OpenFileDialog
{
Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff"
};

if (browseDialog.ShowDialog(this) != DialogResult.Cancel)
{
var fileName = browseDialog.FileName;
CurrentImage = new MyImage
{
FileData = System.IO.File.ReadAllBytes(fileName),
FileName = fileName
};
}
}

///
/// Saves the button click.
///
/// The sender.
/// The instance containing the event data.
private void SaveButtonClick(object sender, EventArgs e)
{
try
{
var filePath = PictureBox.ImageLocation;
var fileData = System.IO.File.ReadAllBytes(filePath);
connection = new OleDbConnection
{
ConnectionString = connectionString
};
connection.Open();

const string statement = @"INSERT INTO Images VALUES(@imageName, @imageData)";
command = new OleDbCommand(statement, connection)
{
CommandType = CommandType.Text
};
command.Parameters.AddWithValue("@imageName", System.IO.Path.GetFileName(filePath));
command.Parameters.AddWithValue("@imageData", fileData);

command.ExecuteNonQuery();
MessageBox.Show("Image saved successfully");
}
catch (Exception exception)
{
MessageBox.Show(string.Format("Error occured {0}", exception.Message));
}
}

///
/// Retrieves the button click.
///
/// The sender.
/// The instance containing the event data.
private void RetrieveButtonClick(object sender, EventArgs e)
{
connection = new OleDbConnection
{
ConnectionString = connectionString
};
connection.Open();

const string statement = @"SELECT * FROM Images ";
command = new OleDbCommand(statement, connection)
{
CommandType = CommandType.Text
};

var dataTable = new DataTable();
dataTable.Load(command.ExecuteReader());
Images = new List();

foreach (DataRow dataRow in dataTable.Rows)
{
Images.Add(new MyImage
{
FileName = dataRow.Field("ImageName"),
FileData = dataRow.Field("ImageData")
});
}

if (Images.Count <= 0)
return;

Images.Sort((x, y) => String.CompareOrdinal(x.FileName, y.FileName));
CurrentImage = Images.FirstOrDefault();
ToggleNavigation();
}

///
/// Binaries to image.
///
/// The image data.
///
private Bitmap BinaryToImage(byte[] imageData)
{
Bitmap image;
using (var stream = new System.IO.MemoryStream(imageData))
{
image = new Bitmap(stream);
}
return image;
}

///
/// Nexts the button click.
///
/// The sender.
/// The instance containing the event data.
private void NextButtonClick(object sender, EventArgs e)
{
var index = Images.IndexOf(CurrentImage);
if (index < Images.Count - 1)
CurrentImage = Images.ElementAt(index + 1);
ToggleNavigation();
}

///
/// Previouses the button click.
///
/// The sender.
/// The instance containing the event data.
private void PreviousButtonClick(object sender, EventArgs e)
{
var index = Images.IndexOf(CurrentImage);
if (index >= 1)
CurrentImage = Images.ElementAt(index - 1);
ToggleNavigation();
}

///
/// Toggles the navigation.
///
private void ToggleNavigation()
{
NextButton.Enabled = Images.IndexOf(CurrentImage) < Images.Count - 1;
PreviousButton.Enabled = Images.IndexOf(CurrentImage) >= 1;
}

}

///
///
///
public class MyImage
{
///
/// Gets or sets the name of the file.
///
///
/// The name of the file.
///
public string FileName { get; set; }

///
/// Gets or sets the file data.
///
///
/// The file data.
///
public byte[] FileData { get; set; }
}
}



Please leave a comment.