First the method preEntities() inserts a new record into the Entities table. One of the inserted values is an image. The data type for this column in the visual studio database is 'image'.
The method loadPanel() is supposed to take the image from every single record in the table (WHERE TYPE = OBSTACLE) and make a picturebox with that image. However there is an error in the FromStream() method: "INVALID PARAMETER"; I put a comment where the error showed up. I searched for previously asked questions about this error but I didn't find anything yet that helped me :(
private void preEntities() {
string constring = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename="
+ "|DataDirectory|\\DonaldJump.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(constring);
con.Open();
byte[] image = ImageToByteArray(Properties.Resources.Pipe);
string q = "INSERT INTO dbo.Entities(Name, Type, Image, Width, Height) VALUES('Pipe','Obstacle','" + image + "','97','150')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
}
private byte[] ImageToByteArray(System.Drawing.Image imageIn) {
using (var ms = new MemoryStream()) {
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
private void loadPanel() {
string constring = "Data Source (LocalDB)\\MSSQLLocalDB;AttachDbFilename="
+ "|DataDirectory|\\DonaldJump.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection con = new SqlConnection(constring);
con.Open();
string q = "SELECT * FROM dbo.Entities WHERE Type='obstacle';";
DataTable dt = new DataTable();
using (var command = new SqlCommand(q, con)) {
using (SqlDataReader dr = command.ExecuteReader()) {
dt.Load(dr);
}
}
foreach (DataRow dr in dt.Rows) {
PictureBox pb = new PictureBox();
pb.Location = new Point(10, 10);
pb.Size = new Size(50, 50);
pb.SizeMode = PictureBoxSizeMode.Zoom;
byte[] img = dr.Field<byte[]>("Image");
MemoryStream mstream = new MemoryStream(img);
pb.Image = Image.FromStream(mstream); //ERROR IS HERE!!!!!!!!!!!!!!!!!!!!!
pb.Name = dr.Field<string>("Name");
pb.Parent = flowLayoutPanel1;
pb.Click += pbClick;
pb.BringToFront();
}
}
You can't concatenate a string with a byte array. The result will be something like 'Pipe','Obstacle','System.Byte[]','97','150'.
You need to use SqlParameter.
First create the query and then add parameters to your command :
string q = "INSERT INTO dbo.Entities(Name, Type, Image, Width, Height) VALUES('Pipe','Obstacle',#image,'97','150')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.Parameters.AddWithValue("image", img);
Related
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;
}
I'm developing an admin panel and a web service but how to add an image data into SQL Server database and retrieve it in admin panel in GridView? Everything adds fine, shows fine except the images. I'm using HTML Input (file) control. No errors just image is not displaying but lblTest shows accordingly.
And how to make my Button can ADD and Refresh so user can see the new data instantly.
Thank you!
Here is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
showSplash();
}
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
Int32 fileLength = 0;
protected void ButtonTest_Click(object sender, EventArgs e)
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\icon\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine with no file";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
My other related question links:
Ajax tabContainer:
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;
}
}
}
}
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.
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.