Error on reading image data from SQL SERVER 2008 R2 - c#

I am creating a windows application and store image in database.
My database is Sql server2008 R2. On insertion image successfully saved to DB, i tried data types image and Varbinary(MAX). In both case on retrieve image it show the error "Parameter is Not Valid". Anyone tell me a solution for this? Is there any change will do in sql server?.
This is my code for retrieve image,
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] img_arr1 = (byte[])dr["img"];
MemoryStream ms1 = new MemoryStream(img_arr1);
ms1.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms1);
}
Code UPDATE from comments:
SqlConnection con1 = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\imgs.mdf;Integrated Security=True;User Instance=true");
con1.Open();
SqlCommand cmd = new SqlCommand("select img from demo1", con1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] img_arr1 = (byte[])dr["img"];
MemoryStream ms1 = new MemoryStream(img_arr1);
ms1.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = Image.FromStream(ms1);
}

Related

How to Display attachments image from access db in picturebox

im trying to display image from database Attachments in picturebox but im getting error on
ImageByte = (byte[]) vcom.ExecuteScalar();
it say
Unable to cast object of type 'System.String' to type 'System.Byte[]'.
here is my code
byte[] ImageByte = null;
MemoryStream MemStream = null;
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/ALL/Database7.accdb";
cn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cn;
string sql = "select Attachments from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
ImageByte = (byte[]) vcom.ExecuteScalar();
MemStream = new MemoryStream(ImageByte);
pictureBox1.Image = Image.FromStream(MemStream);
cn.Close();
In MSAccess, attachments binary data are located in a sub element of the Attachment field.
This will return a byte[]. This byte[] is padded by MSAccess, first 20 bytes are contains MetaData.
You can use Linq .Skip() to get rid of those first 20 bytes
string sql = "select Attachments.FileData from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
byte[] ImageByte = (byte[]) vcom.ExecuteScalar(); //contains 20 extra bytes
MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
Image image = Image.FromStream(MemStream); //Will work now
pictureBox1.Image = image;
...
Does this work?

How to read Arabic text from varchar column?

I have sqlite database who store Arabic text in varchar field
I used this code,but when try to read the value question mark is appear instead character
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt FROM tblQTxt'", con);
con.Open();
SQLiteDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr["Qtxt"].ToString();
dr.Close();
con.Close();
I used "DB Browser for SQLite" fro opening database
when try to view field as binary mode and then export as text I will see the true character
how can read this filed truly?
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt2 FROM tblQTxt where Sore='1' and Aye='1'", con);
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
if (dSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dSet.Tables[0].Rows[0]["Qtxt2"]);
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
StreamReader reader = new StreamReader(ms,Encoding.GetEncoding(1256));
string text = reader.ReadToEnd();
textBox1.Text = text;
}

unable to retrieve image from sql server

I am storing the image from web cam to sql server but unable to retrieve the image back to picture box. Here is code to store image from picture box to sql server.
MemoryStream ms1 = new MemoryStream();
userpic2.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] img_arr1 = new byte[ms1.Length];
ms1.Read(img_arr1, 0, img_arr1.Length);
SqlCommand cmd = new SqlCommand("INSERT INTO CustomerDetails(Photo) values (#pic)", con);
cmd.Parameters.AddWithValue("#pic", img_arr1);
cmd.ExecuteNonQuery();
Code to retrieve image from database to picturebox:-
MemoryStream stream = new MemoryStream();
SqlCommand command = new SqlCommand("select Photo from CustomerDetails where Fname='" + Glist.SelectedItem + "'", con);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);/// here i am getting error as INVALID PARAMETER
userpic2.Image = bitmap;
byte[] bt;
using (SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=true"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID=2", conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
bt = reader["Photo"] as byte[] ?? null;
ImageConverter ic = new ImageConverter();
System.Drawing.Bitmap img = (System.Drawing.Bitmap)ic.ConvertFrom(bt);
pictureBox1.Image = img;
}
}
}
}

Image from SQL Server Table to asp.net image control

SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read() == true)
{
lblHead.Text = sdr["HEADING"].ToString();
lblData.Text = sdr["COMMENT"].ToString();
}
conn.Close();
That is the code for normal data value retrieve from table now I want to get picture from SQL Server that is saved as Binary data that code mention in bottom. So I want to retrieve picture into an Image control of asp.net; please guide me.
if (FileUpload1.HasFile)
{
conn.Close();
String SqlQery;
SqlQery = "select max(CMTID) from FTAB";
SqlCommand cmdid = new SqlCommand(SqlQery, conn);
conn.Open();
MaxID = (int)(cmdid.ExecuteScalar()) + 1;
conn.Close();
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimg = FileUpload1.PostedFile;
myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (#imgid, #image, #comment, #datetm, #heading)", conn);
SqlParameter imgid = new SqlParameter("#imgid",SqlDbType.Int);
imgid.Value = MaxID;
cmd.Parameters.Add(imgid);
SqlParameter uploading = new SqlParameter("#image", SqlDbType.Image);
uploading.Value = img;
cmd.Parameters.Add(uploading);
SqlParameter cmtt = new SqlParameter("#comment", SqlDbType.NVarChar);
cmtt.Value = RadTextBox3.Text;
cmd.Parameters.Add(cmtt);
SqlParameter dttm = new SqlParameter("#datetm", SqlDbType.DateTime);
dttm.Value = DateTime.Now;
cmd.Parameters.Add(dttm);
SqlParameter hhding = new SqlParameter("#heading", SqlDbType.NVarChar);
hhding.Value = RadTextBox8.Text;
cmd.Parameters.Add(hhding);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lblHead.Text = "Image uploaded";
}
else
{
lblHead.Text = "No file selected";
}
Try this
SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
img.ImageUrl = filePath;
But I would say this isn't the best way to do it, you should save your uploaded images as files as in your website and save the path of that file in your database.
yogi's answer is correct in principle, but requires a web server directory "temp" and write access on an IIS directory.
You can also solve the problem using an image handler as explained in another SO question. Database retrieval is done in the same way, but the rendering happens from a stream, rather than a temp file.

Retrieving an image from SQL Server

I wrote this code but faced an exception that said: Parameter Not Valid.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tbl";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
byte[] barrImg = (byte[])dt.Rows[1]["image"];
MemoryStream mstream = new MemoryStream();
mstream.Write(barrImg, 0, barrImg.Length);
mstream.Seek(0, SeekOrigin.Begin);
img.Image = Image.FromStream(mstream);
mstream.Close();
The exception is:
Parameter is not valid.
in the Image.FromStream line of code.
I checked the value that in datatable was assigned to the image field. It was System.Byte[]. I traced the code. Every thing seems to be correct. But it does not work.
I searched around this problem. Another site preferred to set mstream.Position = 0. But that does not work.
I stored my image by this code.If it maybe that I saved this wrong!
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string sql = "INSERT INTO tbl (name, family, image) VALUES ('name', 'family', '{0}')";
sql = string.Format(sql, Image.FromFile("test.jpg"));
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
conn.Close();
new code to save the image:
public byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
and :
private void cmdSave_Click(object sender, EventArgs e)
{
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
byte[] imageData = ReadFile("test.jpg");
SqlConnection CN = new SqlConnection(connstr);
string qry = "insert into tbl (name, family, image) VALUES ('name', 'family', '{0}')";
qry = string.Format(qry, imageData);
SqlCommand SqlCom = new SqlCommand(qry, CN);
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
}
Um, that's not going to work.
Your code that "stores" the image, well, doesn't really do what you think it does.
It is putting the value "test.jpg" into the image field. That isn't the binary image data; only the filename.
So, when you go to pull it back out the Image.FromStream(mstream) call is going to blow chunks because the value "test.jpg" is not an image.. ergo: the parameter is not valid
Here is an example of what you need to be doing to actually put the image into the database:
http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server
You close the stream then try to pull an image from the stream, hence the error "cannot access a closed stream."
Try swapping the order of your last two lines:
img.Image = Image.FromStream(mstream);
mstream.Close();
using (MemoryStream mstream = new MemoryStream((byte[])dt.Rows[1]["image"]))
{
img.Image = Image.FromStream(mstream);
}
Would simplify things. I suspect your problem would be you need to call mStream.Flush() after write and before the seek.
To put an image in to a database, one way is.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
using(SqlConnection conn = new SqlConnection(connstr))
{
using (SqlCommand comm = new SqlCommand(conn))
{
comm.CommandText = "INSERT INTO tbl (name, family, image) VALUES (#name,#family,#Content)";
comm.Parameters.Add(new SqlParameter("name",DbType.String,"Fred"));
comm.Parameters.Add(new SqlParameter("family",DbType.String,"Flintstone"));
using(FileStream fs = new FileStream("FredWilmaBamBamAndDino.jpg",FileMode.Open,FileAccess.Read))
{
comm.Parameters.Add(new SqlParameter("content",DbType.Image,fs));
}
cmd.ExecuteNonQuery();
}
}
Notice it puts the content of teh file in the database. Since in the case of a jpg that content is most definitely not a string, use a parameterised query. Which youi should be doing anyway, develop a good habit.
You also need to suss out using, your code was leaking resources all over the place.

Categories