unable to retrieve image from sql server - c#

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

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?

c# FromStream(stream) invalid parameter?

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

Error on reading image data from SQL SERVER 2008 R2

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

Image Save and Retrieve in SQL Server in asp.net using c#

I am trying to save images in a SQL Server database.
I convert the image to bytes and store in SQL Server, but now I want to convert the saved bytes to an image and show it on a label in asp.net using c#.
I tried a lot but didn't find a solution.
Here is the code (convert bytes to Image)
if (fImage.HasFile)
{
if (fImage.PostedFile.ContentType == "image/jpg" || fImage.PostedFile.ContentType == "image/jpeg" || fImage.PostedFile.ContentType == "image/png")
{
int filelenght = fImage.PostedFile.ContentLength;
byte[] imagebytes = new byte[filelenght];
fImage.PostedFile.InputStream.Read(imagebytes, 0, filelenght);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into tbImage(Img) values(#img)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#img", imagebytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Image saved to database");
}
}
Something like this will convert Byte[] to Image:
MemoryStream ms = new MemoryStream(byte);
Image i = Image.FromStream(ms);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
byte[] img = (byte[])reader["img"];
MemoryStream ms = new MemoryStream(img);
PictureBox1.Image = Image.FromStream(ms);
}
}
con.Close();
All you need to do is to store the byte content in a variable and then write it to the File system:
var imgBlob = ... // Load the image binary array from the database
File.WriteAllBytes("path/to/file.jpg", imgBlob);
you can create a controller action to handle retrieving the image
public FileResult DownloadImage(int Photo_Id)
{
byte[] fileBytes = "get bytes from db here";
string fileName = "file name here"
return File(fileBytes, "contentType of the image" , fileName);
}
Thanks for your valuable reply.
i solve this problem with this one.
give a look.
int id = Convert.ToInt32(drpImage.SelectedValue);
SqlCommand cmd = new SqlCommand("Select img from tbImage where id = " + id+"", con);
con.Open();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
byte[] img = (byte[])dr["img"];
string base64string = Convert.ToBase64String(img, 0, img.Length);
lblImage.Text += "<img src='data:image/png;base64," + base64string + "' alt='No Image' width='200px' vspace='5px' hspace='5px' />";
}
}
con.Close();

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.

Categories