I have a table that have a field as Varbinary(MAX) datatype and I want to insert image file from PictureBox into this column. So how can I convert and insert image to Varbinary in Sql Server. Thank for help me.
You should really show some code, what have you tried...
This is only a guess, but it should give you a clue how to insert picture into database:
//byte array that will hold image data
byte[] imageData = null;
using (var ms = new MemoryStream())
{
//here is image property of your pictureBox control saved into memory stream
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
imageData = ms.ToArray();
}
//make sql connection
SqlConnection conn = new SqlConnection("your connection string goes here");
// command with parameter
SqlCommand cmd = new SqlCommand("insert into TableWithImages (imageData) values (#imageData);", conn);
//define param and pass byte array as value
cmd.Parameters.Add("#imageData", SqlDbType.VarBinary).Value = imageData;
//do insert
cmd.ExecuteNonQuery();
Related
I don't know what's wrong with my code in retrieving image in db. I insert image without using image path file cause the image provide by the cam.
Here's my code in inserting image in db
Image img = pictureBox1.Image;
MemoryStream memStream = new MemoryStream();
img.Save(memStream, ImageFormat.Bmp);
byte[] imageBt = memStream.ToArray();
query = "";
query += "INSERT INTO table(picture) VALUES ('" + imageBt + "')";
cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
con.close();
Here's my code in retrieving image in db
query = "";
query += "SELECT picture FROM table WHERE id = '1'";
cmd = new MySqlCommand(query, con);
con.Open();
MemoryStream ms = new MemoryStream();
byte[] image = (byte[])cmd.ExecuteScalar();
ms.Write(image, 0, image.Length);
con.Close();
Bitmap bmp = new Bitmap(ms)
pictureBox1.Image = bmp; //Still get the Error here parameter is not valid
Is there anywrong process in saving image in database. Btw my image type in db is Blob. I don't know why it doesn't work in retrieving image it always thrown error. Thanks
When reading, you haven't rewound the stream. If you Write, you must set ms.Position = 0; afterwards. Or simpler: create the stream from the data, then you don't need to:
byte[] image = ...
var ms = new MemoryStream(image);
When writing, you seem to have injected the data directly. That... almost certainly won't work - in fact, you're probably writing System.Byte[] to the command. Ideally, use a parameter:
query = "INSERT INTO table(picture) VALUES (#blob)";
cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("blob", imageBt);
cmd.ExecuteNonQuery();
(the exact syntax may change between RDBMS implementations)
I have a table with varbinary column:
My table {
Id int primary key,
FileBody varbinary(max)
}
Now I want to read it. It's simple I can use code like in this answer but it converts varbinary to byte[] and I want to avoid it.
Is it possible to put varbinary in MemoryStream without converting to a byte[]?
You can user a SqlDataReader.GetBytes to read data from the column or use SqlDataReader.GetSqlBytes or SqlDataReader.GetStream
Example :
Using getBytes
SqlCommand command = new SqlCommand( .... );
...
SqlDataReader sqlReader = command.ExecuteReader(CommandBehavior.SequentialAccess);
byte[] outbyte = new byte[bufferSize];
sqlReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
Using GetSqlBytes
SqlCommand command = new SqlCommand( .... );
...
SqlDataReader sqlReader = command.ExecuteReader(CommandBehavior.SequentialAccess);
byte[] outbyte = sqlReader.GetSqlBytes(1).Buffer;
I believe You are searching for this:
SqlCommand command = new SqlCommand();
SqlDataReader reader = command.ExecuteReader();
System.IO.Stream stream = reader.GetStream(1); // 1 is the index of the column
GetStream method:
Retrieves binary, image, varbinary, UDT, and variant data types as a Stream.
I am storing the image in a database and using c# as the front end.
I am storing the image by converting into binary format.
How can I retrieve the image stored in binary format from database?
Maybe this will help:
OdbcConnection con = new OdbcConnection(ConnectString);
con.Open();
OdbcCommand checkcommand = new OdbcCommand("SELECT contents FROM MyTable WHERE MyClause", con);
OdbcDataReader checkreader = checkcommand.ExecuteReader();
byte[] array = null;
if (checkreader.Read())
array = (byte[])checkreader.GetValue(0);
else
{
//Error
return false;
}
File.WriteAllBytes("C:\\MyImage.jpeg", array);
I want to retrieve the images from SQL table and save it in the list and show it in my listview. But I don't know how to do this. I need your help.
I am using SQL Server 2008, Visual Studio 2008, C# Window Application.
Here is my code:
cmd = new SqlCommand("Select ScanImage from ScanDocuments", con);
dr = cmd.ExecuteReader();
List<ImageList> lstitem = new List<ImageList>();
while (dr.Read())
{
ImageList _image = new ImageList();
byte[] data = (byte[])dr["ScanImage"];
MemoryStream ms = new MemoryStream(data);
Image bmp = new Bitmap(ms);
lstitem.Add(bmp);
}
Your code has several flaws - you need to use something like this instead:
// define connection string and select statement
// I used AdventureWorks 2012 database - change to match *YOUR* environment
string connectionString = "server=.;database=AdventureWorks2012;integrated security=SSPI;";
string query = "SELECT ThumbNailPhoto FROM Production.ProductPhoto";
// define a list of "Image" objects
List<Image> listOfImages = new List<Image>();
// using the SqlConnection and SqlCommand ....
using(SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
// open connection
conn.Open();
// execute SqlCommand to return a SqlDataReader
using (SqlDataReader rdr = selectCmd.ExecuteReader())
{
// iterate over the reader
while (rdr.Read())
{
// load the bytes from the database that represent your image
var imageBytes = (byte[]) rdr[0];
// put those bytes into a memory stream and "rewind" the memory stream
MemoryStream memStm = new MemoryStream(imageBytes);
memStm.Seek(0, SeekOrigin.Begin);
// create an "Image" from that memory stream
Image image = Image.FromStream(memStm);
// add image to list
listOfImages.Add(image);
}
}
conn.Close();
}
This works just fine for me - it loads the 101 ThumbNailPhoto from the AdventureWorks2012 database
I'm developing an app in C# with .NET and MySQL database. I need to be able to insert and retrieve images in and out of the database and I have a column named 'Image' of type LONGBLOB for that purpose. The insertion goes well but when I try to retrieve the blob the following error pops up:
GetBytes() can only be called on binary or GUID columns
I'm using the following code to select from the database:
Conn.Open();
string sql = #"SELECT `ID`, `Image`, `Note`"
+ " FROM `Item`"
+ " WHERE `ID` = ?ID";
MySqlCommand cmd = new MySqlCommand(sql, Conn);
cmd.Parameters.Add(new MySqlParameter("?ID", iD));
cmd.Prepare();
rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (rdr.Read())
{
this.ID= rdr.GetString("ID");
if (!rdr.IsDBNull(1))
{
long len = rdr.GetBytes(1, 0, null, 0, 0);
byte[] ImageBytes = new byte[len];
rdr.GetBytes(1, 0, ImageBytes, 0, (int)len);
MemoryStream ms = new MemoryStream(ImageBytes);
this.Image = Image.FromStream(ms);
}
this.Note = rdr.GetString("Note");
Despite changing the column type into binary and varbinary, I still got the same error.
Does anyone know what I'm doing wrong here?
TIA
Can't you just cast rdr["Image"] as byte[]?