Loading a Picturebox in C# with an Oracle Blob - c#

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 )

Related

Trying to upload image file to database using input from asp.net page getting error

I am trying to upload an image to a mysql database. I upload the image on a asp.net page . But i am getting this error whenever i try to upload the image to the database.
System.FormatException: 'Input string was not in a correct format.'
on the line with this code
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
This is the complete code that i tried
protected void upload_files(object sender, EventArgs e)
{
if (FileUpload_UploadFile.HasFile)
{
HttpPostedFile img = FileUpload_UploadFile.PostedFile;
// IMPLEMENT YOUR CODE FOR SAVING THE FILE
Console.Write(img);
Stream stream = img.InputStream;
BinaryReader binaryReader = new BinaryReader(stream);
bytes = binaryReader.ReadBytes((int)stream.Length);
result = System.Text.Encoding.UTF8.GetString(bytes);
myLabel2.Text = "file has been uploaded";
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql_command = "Insert INTO Recognized_person1 (Name,Image,Department,Department_id) VALUES (#Name, #Image, #Department, #Department_id )";
conn.Open();
MySqlCommand MyCommand2 = new MySqlCommand(sql_command, conn);
MyCommand2.Parameters.AddWithValue("#Name", MySqlDbType.VarChar).Value = Name.Text;
MyCommand2.Parameters.AddWithValue("#Image", MySqlDbType.Blob).Value = bytes;
MyCommand2.Parameters.AddWithValue("#Department", MySqlDbType.VarChar).Value = Department.Text ;
MyCommand2.Parameters.AddWithValue("#Department_id", MySqlDbType.Int32).Value = Int32.Parse((Department_id1.Text));
//MyCommand2.ExecuteNonQuery();
MySqlDataReader MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
}
conn.Close();
}
}
Any ideas on how to correct this error ?

Replacing an image in a database with c# (using UPDATE)

I have a database with images stored in it and I want to replace those images with new ones. Here is the thing: I have a picturebox and in this picturebox I am downloading an image. This image is the one that I want to use to replace the current image of my databaserow where my column "Id" is 6.
Right now I am trying to do it with UPDATE but it is not working and I am wondering why. Here is my code:
private void buttonReplace_Click(object sender, EventArgs e)
{
string sql = "SELECT * FROM [Insert_Image]"; //name of database
SqlDataAdapter dA = new SqlDataAdapter(sql, cn);
DataTable dT = new DataTable();
dA.Fill(dT);
int z = dT.Rows.Count + 1;
int i = 6;
try
{
cn.Open();
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string strSql = "UPDATE [Insert_Image] SET Picture = " + #img + " WHERE Id LIKE '" + i + "'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
finally
{
cn.Close();
}
}
My Problem is that something is saved in my database, but whatever I am saving with this code is not the binary-code for an image. I checked my filestream and that is correct as I am using the same filestream I used for uploading to the picturebox. I would be very glad for any help or ideas.
do not hard code value in the query, instead use.
cmd.Parameters.Addnew SqlParameter("#img", img));
check this cheet sheet on SQL Injection
string strSql = "UPDATE [tablename] SET Picture=#img WHERE Id LIKE '%#i%'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#i", i));
cmd.ExecuteNonQuery();

Show image on picture box when clicking on datagridview row

I'm in need of some piece of code to help me out to print a Image that is stored on a datagrid row or SQL DB image, and i wanted to do something useful out of it.
My point is to insert a image everytime i click on a datarow.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Trabalhos\AuthMyRegistery\AuthMyRegistery\Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
id_Worker_Info = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id_Worker_Info"].Value.ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Worker where id_Worker_Info='" +id_Worker_Info+ "';";
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
foreach (DataRow dr in dt.Rows)
{
WorkerIdTextBox.Text = dr["id_Worker_Info"].ToString();
NameTextBox.Text = dr["Name"].ToString();
FnameTextBox.Text = dr["Formation_Name"].ToString();
BirthTextBox.Text = dr["Date_of_Birth"].ToString();
}
}
Assuming your data come in from a byte array, e.g. a blob type that contains valid image data this should work:
using System.IO;
..
byte[] iData = (byte[])dr[yourColumnIndexOrName];
Bitmap bmp = null;
if (iData != null)
using (var ms = new MemoryStream(iData ))
{
bmp = new Bitmap(ms);
}
pb_image.Image = bmp; // display in a PictureBox
It is up to you to decide on the SizeMode and the Size of the PictureBox. You can test the bmp.Size, if you want to..
Don't forget to clean up the bitmap before assigning a new one:
if (pb_image.Image != null)
{
Image img = pb_image.Image;
pb_image.Image = null;
img.Dispose();
}

Parameter is no valid when convert byte to image c#

I have done inserting image into database and the datatype is image, but when I want to retrieve it, it is very difficult and error will show Parameter is not valid.
public void RetrieveImage()
{
var con = new SqlConnection(Connection.CATAS_LOCAL());
string SQL = "Select Name,Image from dbo.[TestImage] where Name = 'Test1'";
var cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader Reader = cmd.ExecuteReader();
Reader.Read();
if (Reader.HasRows)
{
txtAddStaffNric.Text = Reader[0].ToString();
byte[] img = (byte[])(Reader[1]);
MemoryStream ms = new MemoryStream(img);
pictureBox2.Image = Image.FromStream(ms); ** error show at this line
}
con.Close();
}

Retrieving data of type SqlDbType.Image from SQL Server CE database

I have the following method i am using to save an object into an SQL Server CE database. I am now stuck on how to get the record back out.
public void SaveRecord(LabRecord _labrecord)
{
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);
sw.Write(_labrecord);
SqlCeCommand sqlCmd = new SqlCeCommand("INSERT INTO LabTransactions([TrasactionType], [CAM], [TransactionObject]) VALUES ('ResultTest', 1234, #Image)", conn);
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, Int32.MaxValue);
sqlCmd.Parameters["#Image"].Value = memStream.GetBuffer();
sqlCmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
Update
I am looking to make another class that returns a specific record.
public LabRecord getRecord(int transactionId)
{
LabRecord returnRecord = null;
try
{
conn = new SqlCeConnection(_connectionString);
conn.Open();
//.... Get the record
}
finally
{
conn.Close();
}
return returnRecord;
}
I think the problem most likely lies in the fact that the size of the #Image parameter is being set to Int32.MaxValue
Set it instead to the length of the image byte stream:
byte[] imgBytes = memStream.GetBuffer();
sqlCmd.Parameters.Add("#Image", SqlDbType.Image, imgBytes.Length);
sqlCmd.Parameters["#Image"].Value = imgBytes;
Here's an excerpt from this example (modified for your question) of how you might go about retrieving the image:
// Get the record
SqlCeCommand cmd = new SqlCeCommand("Select [TransactionObject] From LabTransactions Where [CAM] = 1234", conn);
conn.Open();
SqlCeDataReader sdr = cmd.ExecuteReader();
byte[] imgByteData = Convert.ToByte(sdr.Item("Picture"));
Bitmap bitmap = new Bitmap(new System.IO.MemoryStream(imgByteData));

Categories

Resources