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);
}
}
Related
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 binary data of an image in my database, and I want to display it in an image control in ASP.NET. How? If it is impossible, please find another way to save it in the database and display it in an image control.
Create a regular HTML img element like so:
<img runat="server" id="image" />
And in code behind do this:
image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
Where imageBytes is a byte[].
You are done. The image will be displayed.
Most likely the image is being stored as a byte array in the database. If so, then you can use this:
public static System.Drawing.Image ByteArrayToImage(byte[] bArray)
{
if (bArray == null)
return null;
System.Drawing.Image newImage;
try
{
using (MemoryStream ms = new MemoryStream(bArray, 0, bArray.Length))
{
ms.Write(bArray, 0, bArray.Length);
newImage = System.Drawing.Image.FromStream(ms, true);
}
}
catch (Exception ex)
{
newImage = null;
//Log an error here
}
return newImage;
}
public Byte[] Ret_image(Int32 id)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from tbimage where imageid=#id";
cmd.Connection = con;
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id;
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
Byte[] ar = (Byte[])(dr[1]);
dr.Close();
cmd.Dispose();
return ar;
}
protected void Button2_Click(object sender, EventArgs e)
{
Byte[] ar = Ret_image(Convert.ToInt32(TextBox2.Text));
String st = Server.MapPath("abc.jpg");
FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
fs.Write(ar, 0, ar.Length);
fs.Close();
Image1.ImageUrl = "abc.jpg";
}
Use this event for the button click to retrieve image and call the Ret_Image method here.
In a generic handler (.ashx):
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if(!string.IsNullOrEmpty(context.Request.QueryString["ImageId"]))
{
try
{
string ImageId = context.Request.QueryString["ImageId"].ToString();
ImageDataModel idm = new ImageDataModel();
byte[] ImageData = idm.getImageData(ImageId);
context.Response.ContentType = "image/JPEG";
context.Response.OutputStream.Write(ImageData, 0, ImageData.Length);
}
catch(Exception ex){}
}
}
}
SqlConnection con = new SqlConnection();
string _path;
Using SYstem.IO;
Using System.Data.SQLClient;
//convert Image to binary and save in DB
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
_path = openFileDialog1.FileName;
InsertInSQL(_path);
}
}
private void InsertInSQL(string _path)
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
string strQ = "insert into dbo.PicTBL(Pic)values(#p)";
SqlCommand command = new SqlCommand(strQ,con);
command.Parameters.AddWithValue("#p",ImageToBinary(_path));
con.Open();
command.ExecuteNonQuery();
con.Close();
}
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
//Convert Binary to imge and save in a folder
private void button1_Click_1(object sender, EventArgs e)
{
DataTable dt = Rimage();
foreach (DataRow row in dt.Rows)
{
byte[] b = (byte[])row["Pic"];
Image img = BinaryToImage(b);
img.Save("D:\\NewFolder\\" + row["ID"].ToString() + ".jpg");
}
}
private Image BinaryToImage(byte[] b)
{
if (b == null)
return null;
MemoryStream memStream = new MemoryStream();
memStream.Write(b, 0, b.Length);
return Image.FromStream(memStream);
}
private DataTable Rimage()
{
con.ConnectionString = Pic.Properties.Settings.Default.ConnectionS;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from dbo.PicTBL";
cmd.Connection = con;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
adp.Fill(dt);
return dt;
}
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.
Hey guys , Can anyone help me out to add images in folder and path in sql database in c sharp 2008 in windows application?
Here is some code you can try with this,
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo imageInfo = new FileInfo(File1.Value.Trim());
if (!imageInfo.Exists)
//Show msg for "please select one image file."
else
{
switch (imageInfo.Extension.ToUpper())
{
case ".JPG": this.UpLoadImageFile(imageInfo); break;
case ".GIF": this.UpLoadImageFile(imageInfo); break;
case ".BMP": this.UpLoadImageFile(imageInfo); break;
default: //Show msg "file type error."; break;
}
}
}
private void UpLoadImageFile(FileInfo info)
{
SqlConnection objConn = null;
SqlCommand objCom = null;
try
{
byte[] content = new byte[info.Length];
FileStream imagestream = info.OpenRead();
imagestream.Read(content, 0, content.Length);
imagestream.Close();
objConn = new SqlConnection(strConnectionString);
objCom = new SqlCommand("insert into TableName(FieldName,Picture)values(#FieldName,#Picture)", objConn);
SqlParameter FieldNameParameter = new SqlParameter("#FieldName", SqlDbType.NVarChar);
if (this.txtFileName.Text.Trim().Equals(""))
FieldNameParameter.Value = "Default";
else
FieldNameParameter.Value = this.txtFileName.Text.Trim();
objCom.Parameters.Add(FieldNameParameter);
SqlParameter pictureParameter = new SqlParameter("#Picture", SqlDbType.Image);
pictureParameter.Value = content;
objCom.Parameters.Add(pictureParameter);
objConn.Open();
objCom.ExecuteNonQuery();
objConn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
objConn.Close();
}
}
Check this ImagesToDatabase
Sample code if you have the path
byte[] img = File.ReadAllBytes("your image path");
mySqlCommand = "INSERT INTO MyTable(Image) VALUES(#Image)";//mySqlCommand is a SqlCommand, and #Image is a parameter
mySqlCommand.Parameters.AddWithValue("#Image", img);
mySqlCommand.ExecuteNonQuery();
If you are using Windows form its nice to save picture as image file in database. Following code may help you:
OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = JPG|*.jpg|GIF|*.gif|PNG|*.png|BMP|*.bmp";
if (DialogResult.OK == ofDlg.ShowDialog())
{
textBox1.Text = ofDlg.FileName;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
picturebox.Image = new Bitmap(ofDlg.OpenFile());
}
//while saveing in databasew
db.conopen();
byte[] img = File.ReadAllBytes(image);
string query = "update tbl_emp_info set EMP_PHOTO=#image where EMP_ID=#empid";
cmd=new SqlCommand(query,db.con);
cmd.Parameters.AddWithValue("#Image",img);
cmd.Parameters.AddWithValue("empid", Emp_id);
cmd.ExecuteNonQuery();