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();
Related
This question already has answers here:
How to store c# imagesource into database ?
(2 answers)
Storing images in SQL Server?
(8 answers)
Convert memory stream to BitmapImage?
(2 answers)
Closed 10 months ago.
I would like to insert image to my database. After clicking button the image should be retrieved from database and showed. How to do it?
Thats what I am sending to database:
//Send my img
private void SendImageMessageClicked(object sender, MouseButtonEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Images PNG (.png)|*.png";
if (openFileDialog.ShowDialog() == true)
{
string message = imageToByteArray(System.Drawing.Image.FromFile(openFileDialog.FileName)).ToString();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO messages VALUES(null, " + userId + ", " + secondUserId + ", '" + message + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
writeMessage.Text = "";
con.Close();
}
}
// convert image to byte array
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
That is how I am trying to get it back:
while (dr.Read())
{
BitmapImage image = new BitmapImage();
MemoryStream stream;
stream = new MemoryStream(Encoding.ASCII.GetBytes((string)dr[3]));
image.BeginInit();
image.StreamSource = stream;
image.EndInit();
imgMsg.Source = image;
}
this is example code, how to INSERT image (u should use VARBINARY(MAX) type in column):
Image image = Image.FromFile(#"D:\test\pictures\react-redux.png");
byte[] imageAsByteArr = ImageToByteArray(image);
using (SqlCommand command = new SqlCommand("insert into ImageTable values(2,#binaryValue)", conn))
{
command.Parameters.Add("#binaryValue", SqlDbType.VarBinary, imageAsByteArr.Length).Value = imageAsByteArr;
command.ExecuteNonQuery();
}
code above is using ImageToByteArray(...):
https://stackoverflow.com/a/3801289/12262729
when it comes to retrieve this data, let read this answer:
https://stackoverflow.com/a/7724595/12262729
after u retrieved data, let convert it to image:
https://stackoverflow.com/a/27774058/12262729
here is my code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from StudentInformation where [StudentID] = " + txtStudentID.Text + "";
command.CommandText = query;
OleDbDataReader read = command.ExecuteReader();
while (read.Read())
{
txtStudentID.Text = (read["StudentID"].ToString());
txtFirstname.Text = (read["Firstname"].ToString());
txtLastname.Text = (read["Lastname"].ToString());
byte[] imgbyte = (byte[])read["Image"]; //when i add this a got error with this code
MemoryStream ms = new MemoryStream(imgbyte);
StudentPicture.Image = Image.FromStream(ms);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
i get the error "Parameter is not valid"
someone can help me?
im so confused!
i tried all the codes what i searched but still Error :'(
sorry for my bad english
Your response will be greatly appreciated....
Try getting your byte array like this instead:
var binLength = read.Item[3].Length;
byte[] imgByte = new byte[binLength - 1];
var bytes = read.GetBytes(0,0,imgByte,0,imgByte.Length);
MemoryStream ms = new MemoryStream(imgByte);
StudentPicture.Image = Image.FromStream(ms);
I am trying to save and read back pdf files in a SQL Server CE local database. I was able to save them as binary data in an Image column, but I don't know how to read them back and open the pdf file (original format).
Table Schema
Here is how I stored the PDF files:
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string filePath = textBox1.Text.ToString();
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
cmd.Parameters.AddWithValue("#Data",bytes);
cmd.ExecuteNonQuery();
} }
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
con.Dispose();
}
Try this
try
{
SqlCeConnection con = new SqlCeConnection(#"Data Source = D:\C# Projects\StoreFileSqlCe\StoreFileSqlCe\Test_File_Stotage.sdf");
con.Open();
string strQuery = "select Data where Name = #Name and ContentType = #ContentType";
SqlCeCommand cmd = new SqlCeCommand(strQuery, con);
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/vnd.ms-word");
SqlCeDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
if (reader.Read())
{
byte[] pdf = (byte[])reader["Data"];
File.WriteAllBytes(filename, pdf);
}
}
}
This is my code; I try to retrieve image. I try to resolve but fail:
SqlCommand cmd = new SqlCommand("select pic from pic where idimg= '" + listBox1.Text + "'", con);
SqlDataReader r;
con.Open();
r = cmd.ExecuteReader();
while (r.Read())
{
byte[] storedImage = (byte[])(r["pic"]);
MemoryStream ms = new MemoryStream(storedImage);
pictureBox1.Image = Image.FromStream(ms); // Error :Parameter is not valid
}
r.Close();
con.Close();
parameter is not valid is only show.while image save on db without given perimeter and no error is generate the error is occurring while retrieve from DB
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.