i am using secugen fingerprint reader and sdk ...with sdk i am able to scan fingerprint,match,verify and display fingerprint image in pictureBox on runtime.. but not able to save in database.. i trien my on code to save fingerprints in database..
this is insertion code
private void BtnVerify_Click(object sender, EventArgs e)
{
Int32 iError;
bool matched1 = false;
bool matched2 = false;
SGFPMSecurityLevel secu_level;
secu_level = (SGFPMSecurityLevel)comboBoxSecuLevel_V.SelectedIndex;
iError = m_FPM.MatchTemplate(m_RegMin1, m_VrfMin, secu_level, ref matched1);
iError = m_FPM.MatchTemplate(m_RegMin2, m_VrfMin, secu_level, ref matched2);
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
if (matched1 & matched2)
{
StatusBar.Text = "Verification Success";
//string name = "sumi";
SqlConnection con = new SqlConnection("Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string qry = "INSERT into teacher_fingerprint (teacher_id,name,teacher_fingerprints)values (#teacher_id,#name,#teacher_fingerprints)";
SqlCommand cmd = new SqlCommand(qry, con);
MemoryStream stream = new MemoryStream();
pictureBoxV1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
con.Open();
cmd.Parameters.AddWithValue("#teacher_id", comboBox2.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text + " " + textBox3.Text);
//cmd.Parameters.AddWithValue("#teacher_fingerprints", m_VrfMin);
cmd.Parameters.AddWithValue("#teacher_fingerprints",pic);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
StatusBar.Text = "Verification Failed";
}
}
else
DisplayError("MatchTemplate()", iError);
}
and this my DrawImage function
private void DrawImageImg(Byte[] imgData, PictureBox picBox)
{
int colorval;
Bitmap bmp = new Bitmap(m_ImageWidth, m_ImageHeight);
picBox.Image = (Image)bmp;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
colorval = (int)imgData[(j * m_ImageWidth) + i];
bmp.SetPixel(i, j, Color.FromArgb(colorval, colorval, colorval));
}
}
picBox.Refresh();
}
this my database .. i dont know this fingerprint binary is valid or not?
enter image description here
i tried to select fingerprint data in pictureBox but its not working
it gives out of index error in drawImage function
this is my selection code
m_RegMin5 = new Byte[400];
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
DrawImage(fp_image, pictureBox1);
StatusBar.Text = "Device Message: Finger On";
SqlConnection conn = new SqlConnection(#"Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string query = "select teacher_fingerprints from teacher_fingerprint where teacher_id=2 ";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
m_RegMin5 = cmd.ExecuteScalar() as byte[];
DrawImageImg(m_RegMin5,pictureBox2);
}
else
{
DisplayError("GetImage()", iError);
}
Related
I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_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)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.
I have a problem with the code c# below, i should save a binary image in a sql server database 2014, i did the function to convert the image to binary, the image select it with a button, The problem is that when I save the database to 0x00 in the field Immagine, how can I fix this type of error? the Immagine field format is binary
QUERY:
private void buttonCaricaImmagine_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
//For any other formats
of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
if (of.ShowDialog() == DialogResult.OK)
{
pictureBoxRapportino.ImageLocation = of.FileName;
imm = pictureBoxRapportino.Image;
checkImage = 1;
}
}
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(imageIn, typeof(byte[]));
return xByte;
}
private void buttonInserimento_Click(object sender, EventArgs e)
{
try
{
if(checkImage==1 && textBoxNumeroDocumento.Text != "")
{
//controlla dati
int NumeroDocumento = int.Parse(textBoxNumeroDocumento.Text);
byte[] ImmagineBinaria = ImageToByteArray(imm);
string BinaryImageCast = Encoding.UTF8.GetString(ImmagineBinaria);
//MessageBox.Show("Immagine in formato binario: " + BinaryImageCast);
//inserisco i dati nel database
SqlConnection conn = db.apriconnessione();
String query = "Insert into Rapporto(IdCantiere,IdUtenteCreazione,NumeroDocumento,Data,Immagine) values(#IdCantiere,#IdUtenteCreazione,#NumeroDocumento,#Data,#Immagine) ";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.Add("#IdCantiere", SqlDbType.Int).Value = IdCantiere;
command.Parameters.Add("#IdUtenteCreazione", SqlDbType.Int).Value = u.IdUtente;
command.Parameters.Add("#NumeroDocumento", SqlDbType.Int).Value = int.Parse(textBoxNumeroDocumento.Text);
command.Parameters.Add("#Data", SqlDbType.DateTime).Value = dateTimePickerData.Value;
command.Parameters.Add("#Immagine", SqlDbType.Binary).Value = ImmagineBinaria;
command.ExecuteNonQuery();
}
db.chiudiconnessione();
conn.Close();
}
else
{
MessageBox.Show("Devi compilare tutti i campi");
}
}
catch(Exception ex)
{
MessageBox.Show("Errore: controlla i formati "+ex);
}
}
Database Sql Server:
Table Schema
CREATE TABLE Rapporto(
IdRapporto int IDENTITY(1,1) PRIMARY KEY,
IdCantiere int FOREIGN KEY REFERENCES Cantiere(IdCantiere),
IdUtenteCreazione int FOREIGN KEY REFERENCES Utente(IdUtente),
NumeroDocumento varchar(5000) default NULL,
Data datetime default NULL,
Immagine varbinary(MAX) default NULL,
);
Try this use conv_photo() this will help you.
private void buttonCaricaImmagine_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
//For any other formats
of.Filter = "Image Files (*.bmp;*.jpg;*.jpeg,*.png)|*.BMP;*.JPG;*.JPEG;*.PNG";
if (of.ShowDialog() == DialogResult.OK)
{
pictureBoxRapportino.ImageLocation = of.FileName;
imm = pictureBoxRapportino.Image;
checkImage = 1;
}
}
//this will convert your picture and save in database
void conv_photo()
{
MemoryStream ms;
if (pictureBoxRapportino.Image != null)
{
ms = new MemoryStream();
pictureBoxRapportino.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo_aray = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo_aray, 0, photo_aray.Length);
command.Parameters.Add("#Immagine", SqlDbType.Binary).Value = photo_aray;
}
}
private void buttonInserimento_Click(object sender, EventArgs e)
{
try
{
if (checkImage == 1 && textBoxNumeroDocumento.Text != "")
{
//controlla dati
int NumeroDocumento = int.Parse(textBoxNumeroDocumento.Text);
//inserisco i dati nel database
SqlConnection conn = db.apriconnessione();
String query = "Insert into Rapporto(IdCantiere,IdUtenteCreazione,NumeroDocumento,Data,Immagine) values(#IdCantiere,#IdUtenteCreazione,#NumeroDocumento,#Data,#Immagine) ";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.Add("#IdCantiere", SqlDbType.Int).Value = IdCantiere;
command.Parameters.Add("#IdUtenteCreazione", SqlDbType.Int).Value = u.IdUtente;
command.Parameters.Add("#NumeroDocumento", SqlDbType.Int).Value = int.Parse(textBoxNumeroDocumento.Text);
command.Parameters.Add("#Data", SqlDbType.DateTime).Value = dateTimePickerData.Value;
conv_photo();
command.ExecuteNonQuery();
}
db.chiudiconnessione();
conn.Close();
}
else
{
MessageBox.Show("Devi compilare tutti i campi");
}
}
catch (Exception ex)
{
MessageBox.Show("Errore: controlla i formati " + ex);
}
}
the code works to a certain extent when I export the data to excel it works fine but if I go back into the application and add, delete or update any of the datagrid when I export the data again it doesn't export the changes. I have deleted the original csv file in case it was an overwriting problem but still get the same problem.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class FormAccounts : Form
{
String constring = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Accounts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
//String cmdselect = #"select * Accounts";
String cmdupdate = #"update Accounts set date = #date, moneyin = #moneyin, retailin = #retailin, rent = #rent, stock = #stock, transport = #transport, misc = #misc, bills = #bills, comments = #comments where ID = #id";
String cmdinsert = #"insert into Accounts (date, moneyin, retailin, rent, stock, transport, misc, bills, comments) values (#date, #moneyin, #retailin, #rent, #stock, #transport, #misc, #bills, #comments )";
String cmddelete = #"delete from Accounts where ID =#ID";
public FormAccounts()
{
InitializeComponent();
}
private void FormAccounts_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'accountsDataSet.Accounts' table. You can move, or remove it, as needed.
this.accountsTableAdapter.Fill(this.accountsDataSet.Accounts);
}
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(cmdinsert, con);
try
{
da.InsertCommand.Parameters.Add("#date", SqlDbType.Date);
da.InsertCommand.Parameters["#date"].Value = dtpaccs.Value;
da.InsertCommand.Parameters.Add("#moneyin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#moneyin"].Value = textmoneyin.Text ;
da.InsertCommand.Parameters.Add("#retailin", SqlDbType.Decimal);
da.InsertCommand.Parameters["#retailin"].Value = textretailin.Text;
da.InsertCommand.Parameters.Add("#rent", SqlDbType.Decimal);
da.InsertCommand.Parameters["#rent"].Value = textrent.Text;
da.InsertCommand.Parameters.Add("#stock", SqlDbType.Decimal);
da.InsertCommand.Parameters["#stock"].Value = textstock.Text;
da.InsertCommand.Parameters.Add("#transport", SqlDbType.Decimal);
da.InsertCommand.Parameters["#transport"].Value = texttransport.Text;
da.InsertCommand.Parameters.Add("#misc", SqlDbType.Decimal);
da.InsertCommand.Parameters["#misc"].Value = textmisc.Text;
da.InsertCommand.Parameters.Add("#bills", SqlDbType.Decimal);
da.InsertCommand.Parameters["#bills"].Value = textbills.Text;
da.InsertCommand.Parameters.Add("#comments", SqlDbType.VarChar);
da.InsertCommand.Parameters["#comments"].Value = textcomments.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
cleartexts();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string date = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
lbldate.Text = date;
lblID.Text = id;
dtpaccs.Value = Convert.ToDateTime(date);
textmoneyin.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
textretailin.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
textrent.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
textstock.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();
texttransport.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
textmisc.Text = dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString();
textbills.Text = dataGridView1.Rows[e.RowIndex].Cells[8].Value.ToString();
textcomments.Text = dataGridView1.Rows[e.RowIndex].Cells[9].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = new SqlCommand(cmdupdate, con);
try
{
da.UpdateCommand.Parameters.Add("#ID", SqlDbType.Int).Value = lblID.Text;
da.UpdateCommand.Parameters.Add("#date", SqlDbType.Date).Value = lbldate.Text;
da.UpdateCommand.Parameters.Add("#moneyin", SqlDbType.Decimal).Value = textmoneyin.Text;
da.UpdateCommand.Parameters.Add("#retailin", SqlDbType.Decimal).Value = textretailin.Text;
da.UpdateCommand.Parameters.Add("#rent", SqlDbType.Decimal).Value = textrent.Text;
da.UpdateCommand.Parameters.Add("#stock", SqlDbType.Decimal).Value = textstock.Text;
da.UpdateCommand.Parameters.Add("#transport", SqlDbType.Decimal).Value = texttransport.Text;
da.UpdateCommand.Parameters.Add("#misc", SqlDbType.Decimal).Value = textmisc.Text;
da.UpdateCommand.Parameters.Add("#bills", SqlDbType.Decimal).Value = textbills.Text;
da.UpdateCommand.Parameters.Add("#comments", SqlDbType.VarChar).Value = textcomments.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
MessageBox.Show("Accounts Updated");
con.Close();
cleartexts();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
var rindex = dataGridView1.SelectedCells[0].RowIndex;
SqlConnection con = new SqlConnection(constring);
SqlDataAdapter da = new SqlDataAdapter();
da.DeleteCommand = new SqlCommand(cmddelete, con);
try
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to delete this record", "Confirmation", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
da.DeleteCommand.Parameters.Add("#ID", SqlDbType.Int).Value = accountsDataSet.Accounts[rindex].ID;
con.Open();
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Record Deleted");
con.Close();
cleartexts();
}
else
{
MessageBox.Show("Delete Cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public void cleartexts()
{
//Clears textboxes
textmoneyin.Text = "";
textretailin.Text ="";
textrent.Text = "";
textstock.Text = "";
texttransport.Text = "";
textmisc.Text = "";
textbills.Text = "";
textcomments.Text = "";
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
int cols;
string directory = #"C:\Users\kenny\Documents\Visual Studio 2010\Projects\Cegees 181013\WindowsFormsApplication1\WindowsFormsApplication1\Excel Exports";
string filename = string.Format("{0:dd-MM-yy}__{1}.csv", DateTime.Now, "Accounts");
string path = Path.Combine(directory, filename);
//open file
using (StreamWriter wr = File.CreateText(path))
{
//determine the number of cols and write to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
wr.Close();
MessageBox.Show("Operation Complete " +path);
}
}
}
}
Found the problem. The application needs to be shut down and restarted for the new data to copy over. Is there a way to do that once the datagrid has been changed / updated?
I want to retrieve an image from an Oracle database to an Image control in asp.net. I tried but it's not working.
This is the code used for inserting image into database:
protected void btnUpload_Click(object sender, EventArgs e)
{
int imgLength = 0;
string imgContentType = null;
string imgFileName = null;
Stream imgStream = FileUpload.PostedFile.InputStream;
imgLength = FileUpload.PostedFile.ContentLength;
imgContentType = FileUpload.PostedFile.ContentType;
imgFileName = FileUpload.PostedFile.FileName;
if (imgContentType == "image/jpeg" || imgContentType == "image/gif" ||
imgContentType == "image/pjpeg"
|| imgContentType == "image/bmp")
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
FileStream fls;
fls = new FileStream(#imgFileName, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
string query = "insert into image(id,name,photo) values(1,'" + imgFileName + "'," + " :BlobParameter )";
// Establish a new OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.CommandText = query;
cmd.Connection = DbConnection;
cmd.CommandType = CommandType.Text;
System.Data.OracleClient.OracleParameter paramImage = new System.Data.OracleClient.OracleParameter("image",
Oracle.DataAccess.Client.OracleDbType.Blob);
paramImage.ParameterName = "BlobParameter";
paramImage.Value = blob;
paramImage.Direction = ParameterDirection.Input;
cmd.Parameters.Add(paramImage);
cmd.ExecuteNonQuery();
}
Table:
Id Name Photo
1 C:\\user\pictures\animal.jpeg (BLOB)
Below is the code used to retrieve the image into an image control but this code is not working.
For the past two days I've been struggling with this
void GetImagesFromDatabase()
{
try
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
OracleCommand cmd = new OracleCommand("Select name,photo from Image", DbConnection);
OracleDataReader oda = cmd.ExecuteReader();
while (oda.Read())
{
string path = oda[0].ToString();
img.ImageUrl = path;
if(oda.GetValue(1).ToString() !=""){
FileStream fls;
fls = new FileStream(#path, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
MemoryStream memStream = new MemoryStream(blob);
img.ImageUrl = oda[2].ToString();
}
}
}
catch (Exception ex)
{
}
}
Any ideas? Thanks in advance
maybe this code can help you:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I have code my system to save a temporary image file to a folder from the pictureBox then I have to make sure that the beginInvoke end and code the system to delete the temporary image file of that folder. Anyone know how to do that?
This is my code:
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
Bitmap bm = new Bitmap(area);
bm.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
singleFileInfo = new FileInfo(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpeg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
var operationStartTime = DateTime.Now;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
operationStartTime = DateTime.Now;
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getImage = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
String getImage1 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[1].Destination.ToString() + "'";
String getImage2 = "SELECT ImageName, ImagePath FROM CharacterImage WHERE ImageName='" + similarityImages[2].Destination.ToString() + "'";
SqlCommand cmd = new SqlCommand(getImage, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
getPath = rd["ImagePath"].ToString();
pictureBox4.Image = Image.FromFile(getPath);
}
rd.Close();
SqlCommand cmd1 = new SqlCommand(getImage1, con);
SqlDataReader rd1 = cmd1.ExecuteReader();
while (rd1.Read())
{
getPath1 = rd1["ImagePath"].ToString();
pictureBox5.Image = Image.FromFile(getPath1);
}
rd1.Close();
SqlCommand cmd2 = new SqlCommand(getImage2, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
getPath2 = rd2["ImagePath"].ToString();
pictureBox6.Image = Image.FromFile(getPath2);
}
con.Close();
}
private void pictureBox4_Click(object sender, EventArgs e)
{
if (pictureBox4.Image == null)
{
MessageBox.Show("Nothing has been scanned yet!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getText = "SELECT ImagePath, Character FROM CharacterImage WHERE ImagePath='" + getPath + "'";
SqlCommand cmd = new SqlCommand(getText, con);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
for (int i = 0; i < 1; i++)
{
String imageChar = rd["Character"].ToString();
Action showText = () => ocrTB.AppendText(imageChar);
ocrTB.Invoke(showText);
}
}
rd.Close();
}
}
BeginInvoke returns you with an IAsyncResult which you can use to wait for the operation to complete:
IAsyncResult result = processImagesDelegate.BeginInvoke(files, processImagesDelegate.EndInvoke, null);
You can then check whether the operation completed using the result.IsCompleted property, or you can wait on the WaitHandle returned from result.AsyncWaitHandle.