picturebox image in c sharp - c#

I'm using these following codes to save picturebox image to database. just i need some code to load picturebox image from database to picturebox.
DialogResult dr = openFileDialog1.ShowDialog();
switch (dr)
{
case DialogResult.Cancel:
break;
case DialogResult.OK:
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
sql = new SqlConnection(#"Data Source=PC-PC\PC;Initial Catalog=Test;Integrated Security=True");
cmd = new SqlCommand();
cmd.Connection = sql;
cmd.CommandText = ("insert [Entry] ([Image]) values (#Image)");
MemoryStream stream = new MemoryStream();
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] image = stream.ToArray();
cmd.Parameters.AddWithValue("#Image", image);
try
{
sql.Open();
cmd.ExecuteNonQuery();
}
finally
{
sql.Close();
}
break;

here there are both code: http://www.codeproject.com/Articles/25956/Sending-Receiving-PictureBox-Image-in-C-To-From-Mi
button2_Click is used to Retrieve the Image:
SqlConnection connect = new SqlConnection
("Server=.;database=PictureDb;integrated security=true");
SqlCommand command = new SqlCommand
("select fldPic from tblUsers where fldCode=1", connect);
//for retrieving the image field in SQL SERVER EXPRESS
//Database you should first bring
//that image in DataList or DataTable
//then add the content to the byte[] array.
//That's ALL!
SqlDataAdapter dp = new SqlDataAdapter(command);
DataSet ds = new DataSet("MyImages");
byte[] MyData = new byte[0];
dp.Fill(ds, "MyImages");
DataRow myRow;
myRow = ds.Tables["MyImages"].Rows[0];
MyData = (byte[])myRow["fldPic"];
MemoryStream stream = new MemoryStream(MyData);
//With the code below, you are in fact converting the byte array of image
//to the real image.
pictureBox2.Image = Image.FromStream(stream);

Related

Parameter is invalid exception when retrieving image from database to picturebox

I am retrieving the image from a SQL Server database into a PictureBox in a C# Windows application. The image is a form which I don't know.
I tried this code but it throws a "parameter invalid" exception, and I also go through many answer related to this but didn't work any.
My code:
SqlConnection sql_con = new SqlConnection();
sql_con.ConnectionString = #"Server=abc-14;Database=Abcstudent;User Id=sa; Password=abc;";
if (sql_con.State == ConnectionState.Closed)
sql_con.Open();
try
{
string query = "Select grno, PICStudent from GENREG where grno = 1";
SqlCommand sql_cmd = new SqlCommand(query, sql_con);
sql_cmd.ExecuteNonQuery();
SqlDataAdapter sql_adp = new SqlDataAdapter(sql_cmd);
sql_adp.Fill(sql_ds);
}
catch(Exception ex)
{
}
// code for retrieving image to picture box
try
{
DataRow myRow;
byte[] MyData = new byte[0];
myRow = sql_ds.Tables[0].Rows[0];
MyData = (byte[])myRow["PICStudent"];
MemoryStream stream = new MemoryStream(MyData);
pictureBox1.Image = Image.FromStream(stream); // getting error here
}
catch()
{
}
Database Image
SqlConnection con = new SqlConnection("Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=SSPI;");
con.Open();
SqlCommand cmd = new SqlCommand("select picbox from picture1 where id=1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])ds.Tables[0].Rows[0]["picbox"]);
pictureBox1.Image = new Bitmap(ms);
}
Insead of using Image.FromStream, did you try using ImageConverter?
Sample come of using ImageConverter looks as following.
byte[] filedata = (byte[])myRow["PICStudent"];
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);
This should resolve your issue.
Thanks and regards,
Chetan Ranpariya

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();
}

unable to convert byte[] to image

I am trying to retrieve a picture stored in MS SQL Server database. The type of the column is image. My code is:
try
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream stream = new MemoryStream(image))
{
stream.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(stream);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am continuously getting ArgumentException as Parameter is not valid when I set the pictureBox1.Image property. I tried all the available solutions on the Internet but all in vain.
You are always using a 10000 byte array even if the image is smaller (or larger). Don't manually create the byte[], the DataReader can provide the entire byte array if you ask for it.
byte[] image = reader.GetFieldValue<byte[]>(0);
If you are not using .NET 4.5 you can just ask for the field and cast it manually.
byte[] image = (byte[])reader.GetValue(0);
However the fact that you are only using the first column from the first row you don't need a DataReader at all, just use ExecuteScalar() instead. (I also am cleaning up your code to use proper using statements and switched your ex.Message to ex.ToString() to provide more info in the error dialog).
try
{
using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using(SqlCommand cmd = new SqlCommand(string.Empty, con))
{
cmd.CommandText = "select Picture from Person";
con.Open();
byte[] image = (byte[])cmd.ExecuteScalar();
using (MemoryStream stream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(stream);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Try this :
SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
pictureBox1.Image = Image.FromStream(mStream);
}

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