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
Related
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);
}
How to save image captured using webcam in Wpf application to sqlite database
Here is my code to save .
public static void SaveImageCapture(BitmapSource bitmap)
{
try
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.QualityLevel = 100;
MemoryStream mm = new MemoryStream();
encoder.Save(mm);
byte[] img = mm.GetBuffer();
DataTable dt = new DataTable();
SQLiteConnection con = new SQLiteConnection(#"data source=F:\Mayur\Vistrack\SqliteDatabases\Vistrack");
con.Open();
SQLiteCommand cmd = new SQLiteCommand("insert into img values('" + img + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
}
}
and for Loading image:
BitmapImage bmp = new BitmapImage();
DataTable dt = new DataTable();
SQLiteConnection con = new SQLiteConnection(#"data source=F:\Mayur\Vistrack\SqliteDatabases\Vistrack");
con.Open();
SQLiteCommand cmd = new SQLiteCommand("select * from img", con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
//cmd.ExecuteNonQuery();
con.Close();
byte[] b = (byte[])dt.Rows[0][0];
MemoryStream byteStream = new MemoryStream(b);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();
imgCapture.Source = image;
while assignning image to my image controle imgCapture it's showing :No imaging component suitable to complete this operation was found.
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));
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);
}
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);