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?
Related
I want to insert some data including an image (as bytes) into a database. How can I do this?
Stream fs = img.ImageFile.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] bytes = br.ReadBytes((Int32)fs.Length);
This above is what I have tried
Get file byte
byte[] file = new byte[img.ImageFile.PostedFile.ContentLength];
Your query(as template)
insert into table file values #file
new SqlParameter("#file",file)
New code
[HttpPost]
public ActionResult addimage(HttpPostedFileBase ImageFile)
{
byte[] file = new byte[ImageFile.ContentLength];
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.addimage", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#tname", file);
con.Open();
status = cmd.ExecuteNonQuery();
}
}
}
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;
}
}
}
}
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);
}
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();
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.