unable to convert byte[] to image - c#

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

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

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

File size increase by 1KB after saving it

I am saving an image file in a SQL Server column (datatype varbinary(max)). Code to save file in database:
Stream fs = imgUpload.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
conn.Open();
using (SqlCommand cmd = new SqlCommand("update tbEHUsers set photo=#binaryValue where UserID="+Session["UserID"].ToString(), conn))
{
cmd.Parameters.Add("#binaryValue", SqlDbType.VarBinary, -1).Value = bytes;
cmd.ExecuteNonQuery();
}
conn.Close();
Get image data from SQL Server:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ToString());
con.Open();
SqlCommand CMD = new SqlCommand("SELECT Photo from tbEHUsers where UserID=" + Session["UserID"], con);
SqlDataReader rdr = CMD.ExecuteReader();
byte[] imgArray = null;
while (rdr.Read())
{
imgArray = (byte[])rdr["Photo"];
}
File.WriteAllBytes("D:\\Test12345.jpg", imgArray);
Original size of file which I uploaded was 858KB however after retrieving from database and saving it again using File.WriteAllBytes method it increases to 859KB. Now when I try to open this file I get 'corrupted file error'. The byte array size was same both the time while saving and retrieving.
What am I doing wrong here??
When using FileUpload.PostedFile you need to reset the InputStream to start from the beginning again. So add the following line on top of your code:
imgUpload.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);

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

picturebox image in c sharp

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

Categories

Resources