Insert and retrieve image from database wpf c# [duplicate] - c#

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

Related

ORA-01460: unimplemented or unreasonable conversion requested-uploading files

Following is the code to upload file in party_images table.
protected void upload_Click(object sender, EventArgs e)
{
try
{
using (OracleConnection connection = new OracleConnection(conString))
{
connection.Open();
string filename = Path.GetFileName(FileUpload1.FileName);
string[] tokenize = filename.Split('.');
FileUpload1.SaveAs(Server.MapPath("~/files/") + descBox.Text + "." + tokenize[1]);
string sourceLoc = Server.MapPath("~/files/" + descBox.Text + "." + tokenize[1]);
FileStream fs = new FileStream(sourceLoc, FileMode.Open, FileAccess.Read);
byte[] ImageData = new byte[fs.Length];
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
String block = " BEGIN " +
" INSERT INTO party_images(party_id, sr_no, descr, party_image) VALUES ('"+Session["userId"]+"',"+srNo.Text+",'"+descBox.Text+"."+tokenize[1]+"', :1); " +
" END; ";
OracleCommand cmd = new OracleCommand();
cmd.CommandText = block;
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
OracleParameter param = cmd.Parameters.Add("blobtodb", OracleDbType.LongRaw);
param.Direction = ParameterDirection.Input;
param.Value = ImageData;
cmd.ExecuteNonQuery();
descBox.Text = "";
srNo.Text = "";
}
}
catch (Exception ex) {
ClientScript.RegisterStartupScript(this.GetType(), "unSuccessMessage", "window.onload = function(){ alert('"+ex.Message+"')};", true);
}
finally
{
populateGrid(loadFromDb());
}
}
table description is,
PARTY_ID is VARCHAR2(10)
SR_NO is NUMBER
DESCR is VARCHAR2(50)
PARTY_IMAGE is LONG RAW()
This function is uploading all the files i.e., images,.docx,.pdf,.sql but when I upload any .docx containing screen shots or pictures then the upper error appears.
I have tried the following links,
ORA-01460: unimplemented or unreasonable conversion requested
The requested format conversion is not supported.
ORA-01460: unimplemented or unreasonable conversion requested
But I haven't got any solution. How can I upload any type of file without having this error?
Why are you using LONG RAW to store binary objects? That's a datatype which has been deprecated for over twenty years.
If you define PARTY_IMAGE as a BLOB (or maybe BFILE) you will find it a lot easier to work with. Find out more.

C# Picturebox.Image needs to be loaded twice before it can be used in code

I have a picturebox on a windows form that gets filled with this command:
pBProcess.ImageLocation = Path.GetDirectoryName(processFile) + "\\" + processes[processStep2Nr] + ".png";
After the images is loaded I'm trying to do two things that both only work after I loaded that image twice.
First thing:
Positioning.CenterHorizontally(pBProcess, pBProcess.Image.Width);
Which does this:
public static void CenterHorizontally(this Control control, int Width)
{
Rectangle parentRect = control.Parent.ClientRectangle;
control.Left = (parentRect.Width - Width) / 2;
}
and the second thing I'm trying to do is to save the image to a SQLDatabase.
cmdLine = "INSERT INTO " + processToSave + " (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(cmdLine, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
Boths actions are executed correctly after I load the picturebox.image a second time.
What causes this and how can I fix it?
Edit:
This is how I create the table I want to save the picture to:
//Tabelle wird erstellt und anschließend gefüllt
strInsert = "CREATE TABLE " + processToSave + "(Attributes NVARCHAR(50), Value TINYINT, Picture IMAGE);";
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
sqlCmd.ExecuteNonQuery();
}
strInsert = "INSERT INTO " + processToSave + " (Attributes, Value) VALUES (#Attributes, #Value);";
foreach (ListViewItem item in checkedItems)
{
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Attributes", SqlDbType.NVarChar);
sqlCmd.Parameters["#Attributes"].Value = item.Text;
sqlCmd.Parameters.Add("#Value", SqlDbType.Int);
sqlCmd.Parameters["#Value"].Value = Convert.ToInt32(item.SubItems[1].Text);
sqlCmd.ExecuteNonQuery();
}
}
strInsert = "INSERT INTO " + processToSave + " (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
And this is how I read the picture from the DB:
MemoryStream stream = new MemoryStream();
strInsert = "SELECT [Picture] FROM " + processToLoad;
SqlCommand sqlCmd2 = new SqlCommand(strInsert, connection);
byte[] image = (byte[])sqlCmd2.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
pBProcess.Image = bitmap;
this is NOT working. But when I create a table in the DB called "Bilder" which has only "Picture" with DBType Image and change the code to this:
strInsert = "INSERT INTO Bilder (Picture) VALUES (#Image);";
MemoryStream stream = new MemoryStream();
pBProcess.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] pic = stream.ToArray();
using (SqlCommand sqlCmd = new SqlCommand(strInsert, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
sqlCmd.ExecuteNonQuery();
}
...
MemoryStream stream = new MemoryStream();
strInsert = "SELECT [Picture] FROM Bilder";
SqlCommand sqlCmd2 = new SqlCommand(strInsert, connection);
byte[] image = (byte[])sqlCmd2.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
pBProcess.Image = bitmap;
It actually works. What's wrong in my original code?
I was mixing up two problems here.
The problem with
Positioning.CenterHorizontally(pBProcess, pBProcess.Image.Width);
was fixed by putting this statement into the LoadCompletedEvent of the picturebox.
The second problem was that I actually inserted a lot of rows into my table (attributes + value) and at the end I inserted another row, consisting only of the image. When I read the table looking for the image, I only read the first row (I think) but there was no image to be found. So I changed the code, putting the image into the first row and then changing the commandline:
bool first = true;
foreach (ListViewItem item in checkedItems)
{
if (first)
cmdLine = "INSERT INTO " + processToSave + " (Attributes, Value, Picture) VALUES (#Attributes, #Value, #Image);";
else
cmdLine = "INSERT INTO " + processToSave + " (Attributes, Value) VALUES (#Attributes, #Value);";
using (SqlCommand sqlCmd = new SqlCommand(cmdLine, connection))
{
//Parameter definieren
sqlCmd.Parameters.Add("#Attributes", SqlDbType.NVarChar);
sqlCmd.Parameters["#Attributes"].Value = item.Text;
sqlCmd.Parameters.Add("#Value", SqlDbType.Int);
sqlCmd.Parameters["#Value"].Value = Convert.ToInt32(item.SubItems[1].Text);
if (first)
{
sqlCmd.Parameters.Add("#Image", SqlDbType.Image);
sqlCmd.Parameters["#Image"].Value = pic;
first = false;
}
sqlCmd.ExecuteNonQuery();
}
}

How to display Image using repeater

I have a page to upload a photo into my database. Then when I click upload, the photo has been saved as binary format in database:
protected void Button1_Click(object sender, EventArgs e)
{
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "','" + bytes + "')", con);
con.Open();
cmd.ExecuteNonQuery();
When I am trying to retrieve image then it is not displayed, how to display image using repeater?
Database: menu image
<asp:Image ID="ViewPhotoImage" runat="server" ImageUrl='<%# GetImage(Eval("menu")) %>' Height="190px" Width="180px"/>
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[]) img);
}
I think your problem may be in how you are putting the data into the database. You may not have valid image data in the database at all. Does that code run for you when you upload an image? When I run it it errors out on the sql command because when you implicitly convert a byte[] into a string in c# you get "System.Byte[]" instead of the string representation of the data. You need to convert that byte[] into a binary string. That link has a bunch of ways to do it, and here's your upload code with one of those ways (Not Recommended, see below):
(Edited, see comment below)
Byte[] bytes = null;
string hex = "0";
if (FileUpload1.HasFile)
{
string filename = FileUpload1.PostedFile.FileName;
string filePath = Path.GetFileName(filename);
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
hex = "0x" + BitConverter.ToString(bytes).Replace("-", "");
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES('" + TextBox.Text + "'," + hex + ")", con);
con.Open();
cmd.ExecuteNonQuery();
You also might want to move that sql code into the if block, but maybe that's what you want, just thought i'd mention it in case.
HOWEVER...
I would be remiss if I did not strongly suggest that you parameterize your sql statement to avoid injection attacks. But not only is it better for security, it makes working with the binary data much easier as there is no need to string convert. Here's the relevant code with parameters:
Byte[] bytes = null;
if (FileUpload1.HasFile)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytes = br.ReadBytes((Int32)fs.Length);
}
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("INSERT INTO disc_info (disc_name,menu) VALUES(#disc, #menu)", con);
cmd.Parameters.AddWithValue("#disc", TextBox.Text);
cmd.Parameters.AddWithValue("#menu", bytes);
con.Open();
cmd.ExecuteNonQuery();
Once I did that, your other code worked fine and I was able to see my test images in the repeater. I hope that helps!

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

How to upload image from C# application to SQL Server 2005 [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Upload image to server using C#/.NET and storing filename in DB
How to upload image from a C# application to SQL Server 2005
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try
{
const string SQL = "INSERT INTO [BinaryTable] ([FileName], [DateTimeUploaded], [MIME], [BinaryData]) VALUES (#FileName, #DateTimeUploaded, #MIME, #BinaryData)";
SqlCommand cmd = new SqlCommand(SQL, Conn);
cmd.Parameters.AddWithValue("#FileName", FileName.Text.Trim());
cmd.Parameters.AddWithValue("#MIME", FileToUpload.PostedFile.ContentType);
byte[] imageBytes = new byte[FileToUpload.PostedFile.InputStream.Length + 1];
FileToUpload.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length);
cmd.Parameters.AddWithValue("#BinaryData", imageBytes);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
Conn.Open();
cmd.ExecuteNonQuery();
lit_Status.Text = "<br />File successfully uploaded - thank you.<br />";
Conn.Close();
}
catch
{
Conn.Close();
}
}
http://www.dotnettutorials.com/tutorials/database/upload-files-sql-database-cs.aspx

Categories