Getting ASCII string converted and show on Picturebox - c#

I am using this Topaz Signature Pad and it saves ASCII string upon final signature to the Database. Now i have a Problem i want to get the ASCII string from the database and convert it to an Image and show in a Picturebox Control I have this code below :
private void button4_Click(object sender, EventArgs e)
{
string constring = #"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=SignatureCapture;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
string sql = "select * from SignTable where id =#id";
using (SqlCommand cm = new SqlCommand(sql, con))
{
cm.Parameters.AddWithValue("#id",textBox1.Text);
try
{
using (SqlDataReader rd = cm.ExecuteReader())
{
if (rd.Read())
{
// byte[] imgData = (byte[])rd["signature"];
byte[] imgData = Convert.FromBase64String(rd["signature"].ToString());
using (MemoryStream ms = new MemoryStream(imgData))
{
System.Drawing.Image image = Image.FromStream(ms);
//image.Save(#"C:\Users\Administrator\Desktop\UserPhoto.jpg");
pictureBox1.Image = image;
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("Error: "+ex.ToString());
}
}
}
}
And i get an Exception at this Line which looks thus :
Question is , How can i go about retrieving an ASCII and displaying on a picturebox?
Edit
SHows error at this Code .. At this line :
private void button4_Click(object sender, EventArgs e)
{
string constring = #"Data Source=DESKTOP-FJBB72F\SQLEXPRESS;Initial Catalog=SignatureCapture;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
string sql = "select * from SignTable where id =#id";
using (SqlCommand cm = new SqlCommand(sql, con))
{
cm.Parameters.AddWithValue("#id",textBox1.Text);
try
{
using (SqlDataReader rd = cm.ExecuteReader())
{
if (rd.Read())
{
// byte[] imgData = (byte[])rd["signature"];
//byte[] imgData = Convert.FromBase64String(rd["signature"].ToString());
byte[]imgData = Encoding.ASCII.GetBytes(rd["signature"].ToString());
using (MemoryStream ms = new MemoryStream(imgData))
{
System.Drawing.Image image = Image.FromStream(ms); // Error shows at this Line <------
//image.Save(#"C:\Users\Administrator\Desktop\UserPhoto.jpg");
pictureBox1.Image = image;
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("Error: "+ex.ToString());
}
}
}
}

Related

"Parameter is not valid" error when retrieving image

I want to retrieve images from a SQL Server database using C#. However, I'm getting the error message
Parameter is not valid
Please help me.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string q = "select * from Rough where name='" + comboBox1.Text + "'";
SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SMS_DB;Integrated Security=True");
SqlCommand cmd = new SqlCommand(q, con);
SqlDataReader dr;
if (con.State == ConnectionState.Closed)
{
con.Open();
dr = cmd.ExecuteReader();
byte[] img = null;
while (dr.Read())
{
textBox1.Text = (dr["ID"].ToString());
textBox2.Text = (dr["Name"].ToString());
textBox3.Text = (dr["Image"].ToString());
img = (byte[])(dr["Image"]);
if (img == null)
{
pictureBox2.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms);
// ms.Close();
}
}
con.Close();
}
}

C# SQLite Table exists and does not exist

private void StartMenu_Load(object sender, EventArgs e)
{
this.CenterToScreen();
if (!File.Exists("schedules.db"))
{
SQLiteConnection.CreateFile("schedules.db");
MessageBox.Show("Created schedules.db");
}
SQLCon = CreateSQLiteConnection();
SQLCon.Open();
using (SQLiteCommand cmd = new SQLiteCommand("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='schedule_ids'", SQLCon))
{
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
using (SQLiteCommand loadSchedules = new SQLiteCommand("SELECT name FROM schedule_ids", SQLCon))
{
reader.Close();
using (SQLiteDataReader reader1 = loadSchedules.ExecuteReader())
{
while (reader1.Read())
{
MessageBox.Show("?");
ScheduleList.Items.Add((string)reader1[0]);
}
MessageBox.Show("$");
}
}
}
else
{
reader.Close();
using (SQLiteCommand createTable = new SQLiteCommand("CREATE TABLE schedules_ids (name nvarchar(45), schedule_id int)", SQLCon))
{
createTable.ExecuteNonQuery();
}
}
}
}
}
private SQLiteConnection CreateSQLiteConnection()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Replace(#"bin\Debug\", "");
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.FailIfMissing = true;
builder.DataSource = Path.Combine(path, "schedules.db");
return new SQLiteConnection(builder.ConnectionString);
}
When I run this (WinForms app), it creates the schedules.db but then I get the error "SQL logic error or missing database no such table: schedule_ids". The weird part is that if I change it from
if (reader.Read())
to
if (!reader.Read())
then I get an error "SQL logic error or missing database table schedule_ids already exists". Any help would be appreciated.
Try a little refactor:
// re-usable variable to avoid typos...
private const string _schedule_Id_TableName = "schedule_ids";
private void StartMenu_Load(object sender, EventArgs e)
{
this.CenterToScreen();
if (!File.Exists("schedules.db"))
{
SQLiteConnection.CreateFile("schedules.db");
MessageBox.Show("Created schedules.db");
}
SQLCon = CreateSQLiteConnection();
SQLCon.Open();
using (SQLiteCommand cmd = new SQLiteCommand(string.Format("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{0}'", _schedule_Id_TableName), SQLCon))
{
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
using (SQLiteCommand loadSchedules = new SQLiteCommand(string.Format("SELECT name FROM {0}", _schedule_Id_TableName), SQLCon))
{
reader.Close();
using (SQLiteDataReader reader1 = loadSchedules.ExecuteReader())
{
while (reader1.Read())
{
MessageBox.Show("?");
ScheduleList.Items.Add((string)reader1[0]);
}
MessageBox.Show("$");
}
}
}
else
{
reader.Close();
// Only create the table if it doesn't already exists...
using (SQLiteCommand createTable = new SQLiteCommand(string.Format("CREATE TABLE IF NOT EXISTS {0}(name nvarchar(45), schedule_id int)", _schedule_Id_TableName), SQLCon))
{
createTable.ExecuteNonQuery();
}
}
}
}
}
private SQLiteConnection CreateSQLiteConnection()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Replace(#"bin\Debug\", "");
SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
builder.FailIfMissing = true;
builder.DataSource = Path.Combine(path, "schedules.db");
return new SQLiteConnection(builder.ConnectionString);
}

Datagridview cell mouseClick event error

can you help me to this problem
i have one form production from where i can upload that photo and save it on to the database,
but when i do a cellmouseclick event it having some problem
and below is the code for doing so:
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
SqlDataReader dr;
private void button2_Click(object sender, EventArgs e)
{
byte[] image = null;
FileStream fs = new FileStream(this.txtLink.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
image = br.ReadBytes ((int)fs.Length);
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto,Photo) Values(#IDProduksi,#IDPhoto,#TanggalProduksi,#NamaKaryawan,#KeteranganPhoto,#Photo)", con);
cmd.Parameters.AddWithValue("#IDProduksi", txtIdpro.Text);
cmd.Parameters.AddWithValue("#IDPhoto", txtIdPhoto.Text);
cmd.Parameters.AddWithValue("#TanggalProduksi", dProduksi);
cmd.Parameters.AddWithValue("#NamaKaryawan", txtNamaKaryawan.Text);
cmd.Parameters.AddWithValue("#KeteranganPhoto", rxtKtrphoto.Text);
cmd.Parameters.AddWithValue("#Photo", image);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
txtIdpro.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
txtIdPhoto.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
dtmProduksi.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
txtNamaKaryawan.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
rxtKtrphoto.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
txtLink.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
// wanna show that picture when you klik cell
byte[] imgg = (byte[])(dr["Photo"]);
MemoryStream Strem = new MemoryStream(imgg);
pictureBox1.Image = System.Drawing.Image.FromStream(Strem);
}
and if i commend that byte[] that can be like that below :
and if i commend that byte[] that can be like that below :
You need to initialize dr. You must create in dataGridView1_CellMouseClick a select query and than you can do this:
dr = cmd.ExecuteReader();
while (dr.Read()) { }

Retrieve Image from Binary Data in SQL to DataList

I am doing a 3 tier application to retrieve image from sql server which i stored image to binary data in sql, and the problem is i can't retrieve my image from the sql server.
here is my code in DataAccessLayer
public List<Volunteer> VolunteerTRetrieve()
{
List<Volunteer> vList = new List<Volunteer>();
byte[] volunteerProfilePicture;
string volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact;
string queryStr = "SELECT * FROM TVolunteer Order By VolunteerName";
SqlConnection conn = new SqlConnection(DBconnStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while ((dr.Read()))
{
volunteerName = dr["VolunteerName"].ToString();
volunteerNRIC = dr["VolunteerNRIC"].ToString();
volunteerAddress = dr["VolunteerAddress"].ToString();
volunteerEmail = dr["VolunteerEmail"].ToString();
volunteerContact = dr["VolunteerContact"].ToString();
volunteerProfilePicture = (byte[])dr["VolunteerProfilePicture"];
vList.Add(new Volunteer(volunteerName, volunteerNRIC, volunteerAddress, volunteerEmail, volunteerContact, volunteerProfilePicture));
}
conn.Close();
dr.Dispose();
return vList;
}
in BusinessLogicLayer
public List<Volunteer> RetrieveAllBVolunteer()
{
Volunteer v = new Volunteer();
List<Volunteer> vList = new List<Volunteer>();
vList = v.VolunteerBRetrieve();
return vList;
}
and in PresentationLayer
List<Volunteer> allVolunteer = new List<Volunteer>();
allVolunteer = vBLL.RetrieveAllTVolunteer();
dl_tvolunteer.DataSource = allVolunteer;
dl_tvolunteer.DataBind();
I have also an image handler class
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DBconnStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string queryStr = "SELECT VolunteerProfilePicture FROM TVolunteer WHERE VolunteerNRIC = #NRIC";
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.Add("#NRIC", SqlDbType.VarChar).Value =
context.Request.QueryString["VolunteerNRIC"];
cmd.Prepare();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["VolunteerProfilePicture"]);
}
Please help, Thankyou!
If you are returning one image you could the following
1. place a PictureBox control on the asp.net webpage
2. define the sql connections //not sure why you are using cmd.prepare
byte[] sqlImage = (byte[])cmd.ExecuteScalar();
MemoryStream memStream = new MemoryStream();
memStream.Write(sqlImage, 0, sqlImage.Length);
Bitmap bit = new Bitmap(memStream);
or if you want to do it a different way
try
{
con = new SqlConnection(constr);
cmd = new SqlCommand("select photopath,Photo from employees where employeeid=14", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
if (!dr.IsDBNull(1))
{
byte[] photo = (byte[])dr[1];
MemoryStream ms = new MemoryStream(photo);
pictureBox1.Image = Image.FromStream(ms);
}
}
}
catch (Exception ex)
{
dr.Close();
cmd.Dispose();
con.Close();
Response.Write(ex.Message);
}

Loading a Picturebox in C# with an Oracle Blob

I've a very basic form with just one picture box,one textfield and one button. I've created a table in Oracle to store a blob, I want to load that image into a picturebox in c# once the button is clicked. Here is what I've wrote so far.
My picturebox name = "picBoxXray". My textbox name = "txtXrayId". My button name = "btnGetXrayID". And My table name is "XRay".
private void btnGetXrayID_Click(object sender, EventArgs e)
{
if (txtXrayId.Text == "")
{
MessageBox.Show("XrayID be entered");
}
if (picBoxXray.Image != null)
{
picBoxXray.Image.Dispose();
}
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM XRay WHERE XrayID =" + txtXrayId.Text;
OracleCommand cmd = new OracleCommand(sql, connection);
OracleDataReader dr = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
// Obtain the image
//Need code
}
command.CommandText = sql;
command.ExecuteNonQuery();
connection.Close();
}
Any help would be greatly aprreciated,
Thanks
You have to create the image from a stream, for example:
public Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
Then aassign the image to the picture box. the byteArray in is the blob you read from the db. of course the image have to be stored in a format known ( png/jpeg for instance )

Categories

Resources