cnn.Open();
cmd.CommandText = "select * from Slab where s_flatno=" + textBox1.Text;
SqlDataReader dr1;
dr1 = cmd.ExecuteReader();
while (dr1.Read())
{
byte[] img1 = File.ReadAllBytes(dr1[7].ToString());
MemoryStream ms = new MemoryStream(img1);
Image img = Image.FromStream(ms);
dataGridView1.Rows.Add(dr1[1].ToString(), dr1[4].ToString(), dr1[5].ToString(), dr1[6].ToString(),dr1[7].ToString());
count = Convert.ToInt32(dataGridView1.Rows.Count.ToString());
}
lblcount.Text = count.ToString();
dr1.Close();
cnn.Close()
In the above code i'm accessing data from database to data grid view but in the table im having images in byte code, how can i convert images from byte to image and how can i update in DataGridView in windows application in c#.
You are using ToString() on the reader's column, but that will not work as the data type of the column is byte[]. You should use the following:
byte[] imageData = ( byte[] )dr1[7];
MemoryStream ms = new MemoryStream(imageData);
Image img = Image.FromStream(ms);
dataGridView1.Rows.Add(dr1[1].ToString(), dr1[4].ToString(), dr1[5].ToString(), dr1[6].ToString(),dr1[7].ToString());
count = Convert.ToInt32(dataGridView1.Rows.Count.ToString());
As additional suggestion, you should use clearer variable names as and definitely access the columns in data reader by column name instead of index, because this will break anytime a change in DB happens and the order of columns changes.
Related
I have this code:
private void LoginBTN_Click(object sender, EventArgs e)
{
var loguser = AutorizeLoginBox.Text;
var passuser = AutorizePasswordBox.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable table = new DataTable();
string querystring = $"select ID, USERLOGIN, USERPASSWORD, USERAVATAR from USERTESTDB where USERLOGIN='{loguser}' and USERPASSWORD='{passuser}'";
SqlCommand command = new SqlCommand(querystring, sqldb.getConnection());
adapter.SelectCommand = command;
adapter.Fill(table);
if (table.Rows.Count == 1)
{
byte[] arr;
Image imgcur;
ImageConverter converter = new ImageConverter();
arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString(), );
MemoryStream ms = new MemoryStream(arr);
Image i = Image.FromStream(ms);
Program.programpg.avatarbox.Image = i;
}
}
How to upload the image assigned to this user in the database after login. //symbolforfixdetails//symbolforfixdetails//symbolforfixdetails//symbolforfixdetails
This is how the database looks like:
Error is on this line:
arr = (byte[])converter.ConvertFromString(table.Rows[0].ToString() );
Error:
System.NotSupportedException: "ImageConverter cannot convert from System.String."
Try the following code to set the PictureBox.Image from image stored in SQL Server. The code is tested and works as intended.
Part 1: retrieve image from database and set it to PictureBox.Image:
DataTable table = new DataTable();
byte[] arr=null;
using (SqlConnection cn = new SqlConnection(cs))
{
cn.Open();
using (SqlDataAdapter ad = new SqlDataAdapter("select top 1 USERAVATAR from USERTESTDB", cn)) // Replace SQL query with yours
{
ad.Fill(table);
}
}
arr = (byte[])table.Rows[0][0];
// Replace it with [0][3] according to your posted query
System.Drawing.Bitmap bitmap = null;
ImageConverter converter = new ImageConverter();
System.Drawing.Image img =
(System.Drawing.Image)converter.ConvertFrom(arr);
bitmap = (System.Drawing.Bitmap)img;
pictureBox1.Image = bitmap;
Part 2: store image in database:
openFileDialog1.ShowDialog();
string path = openFileDialog1.FileName;
byte[] img = null;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
using (SqlConnection cn = new SqlConnection(cs))
{
cn.Open();
using (SqlCommand cm = new SqlCommand("insert into USERTESTDB Values (#img)",cn))
{
cm.Parameters.Add(new SqlParameter("#img", img));
cm.ExecuteNonQuery();
}
}
You didn't asked about Part2, but I included it to ensure that the image is stored correctly (as binary data) in the database.
You have two problems with your line of code
arr = byte[])converter.ConvertFromString(table.Rows[0].ToString());
You used table.Rows[0] (which returns the entire row) instead of table.Rows[0][x] where x = the index of image column.
You can't convert String to Image in this way, check question 3594239 for more details.
Please Set your Db Column Data type to Varbinary(Max) which you store image's bytes.
Then read this binary to a MemoryStream() as you did but without convert.
If its a winforms project there should be an overload in PictureBox's DataSource (or whatever its name. if i don't remember wrong its name is Image or BackgroundImage) as it accepts directly byte array.
If Winforms, Either you can pass as byte array or Convert to an Image object and set it to datasource.
But if its a web project, then either you could set it as a base64 data/png string or Image object.
Hope this helps.
i call a database to get data in column with data type longtext that contain string that i've encoded from image with base64
string insertQuery = "SELECT product_id, picture FROM product WHERE aksi != 'Deleted' ";
etc...
dataGridView1.DataSource = dtblProduct;
the column with data type longtext is picture
i want to convert the longtext's data in column picture with base64 and display it on gridview along with product id
i've tried, but the error says 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. '
string showpic = dataGridView1.Columns[1].ToString();
byte[] imageBytes = Convert.FromBase64String(showpic);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image myimage = Image.FromStream(ms, true);
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.Image = myimage;
According to your description, you want to display a picture in a column of datagridview.
I suggest that when designing the form, add two columns in the datagridview, namely product_id, picture.
The data type of the picture column is DataGridViewImageColumn.
You can try the following code to solve this problem.
public void Table()
{
dataGridView1.Rows.Clear();
MySqlConnection conn = new MySqlConnection("…");
conn.Open();
MySqlCommand cmd = new MySqlCommand("select product_id,picture from product WHERE aksi != 'Deleted'", conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string id, base64;
id = reader["product_id"].ToString();
base64 = reader["picture"].ToString();
byte[] bytes = Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
BinaryFormatter binFormatter = new BinaryFormatter();
Image img = (Image)binFormatter.Deserialize(memStream);
dataGridView1.Rows.Add(new object[] { id,img});
}
reader.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
Table();
}
Result:
I have a BLOB value in a MySQL database.
I've read several tutorials, but I can not find a solution.
Any idea how I can read the image (blob value) and view it in an ASP.NET Image component?
All info i found is about array convert to image, but I have a Blob value
Did you try to read the image from db and put in a MemoryStream, then show it in an image component? Something like :
Byte[] byteBLOBData = new Byte[bufferSize];
byteBLOBData = "read image from database"
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pictureBox.Image = Image.FromStream(stmBLOBData);
Reference : https://bytes.com/topic/c-sharp/answers/965811-retrieve-blob-picture-mysql-database-c
Problem solved.
The exact problem was the query...
Code finished...
Image picture = new Image();
string queryImage = "SELECT image FROM news WHERE id = #id";
using (MySqlConnection con1 = new MySqlConnection(servidor))
{
MySqlCommand cmd1 = new MySqlCommand(queryImage, con1);
cmd1.Parameters.AddWithValue("#id", rd[0]);
con1.Open();
byte[] bytesImage = (byte[])cmd1.ExecuteScalar();
picture.ImageUrl = "data:image;base64," + Convert.ToBase64String(bytesImage);
}
In C#, I am trying to save and load an image. I am saving it into a mysql database (type longblob) and trying to load it back into an picture box. The problem i keep getting is the error "Parameter is not valid", see code below
ConnectionClass Sqlconnection = new ConnectionClass();
Sqlconnection.ConnectionOpen();
OdbcCommand cmd = new OdbcCommand("Insert into pictest(pic) values('"+ Encoding.Unicode.GetBytes(richTextBox1.Rtf) + "')", Sqlconnection.connection);
int num = cmd.ExecuteNonQuery();
MessageBox.Show(num + " Rows inserted ");
Sqlconnection.ConnectionClose();
OdbcDataReader rd = null;
try
{
Sqlconnection.ConnectionOpen();
string query = "select * from pictest where id = 1";
cmd = new OdbcCommand(query, Sqlconnection.connection);
rd = cmd.ExecuteReader();
if (rd.Read())
{
byte[] bytes = (byte[])rd[1];
ImageConverter converter = new ImageConverter();
pictureBox1.Image = Image.FromStream(new MemoryStream(bytes)); <--Parameter is not valid
pictureBox1.Refresh();
pictureBox1.Image = Encoding.Unicode.GetString(bytes);
}
Sqlconnection.ConnectionClose();
rd.Close();
}
catch (Exception asd)
{
MessageBox.Show("Problem " + asd.Message);
Sqlconnection.ConnectionClose();
if (rd != null)
{
rd.Close();
}
}
what exact is the problem? Is the image not saving correctly? it should be as it is saving to a longblob. The record for the image says System.Byte[]
you should be able to inspect (via the debugger) the values inside OdbcDataReader before trying to cast the first field to byte[]. Take a look at what type is actually stored in the OdbcDataReader
Using SELECT * is problematic performance wise. It also leaves your rd[1] up for interpretation. If the order of columns ever changes, your code could break. Use rd["your_column_name"] to access the values. As of right now I can't tell if index 1 is correct due to the SELECT * and non-named indexing into the Items array.
First of all why you need to store image in MySql?
Why not in physical drive? If its not a crucial data go for saving it in physical drive.
However, here is code to retrieve:
public byte [] getImage(int imageNumber)
{
string strSql = "SELECT * FROM File";
DataSet ds = new DataSet("Image");
OdbcDataAdapter tempAP = new OdbcDataAdapter(strSql,this._objConn);
OdbcCommandBuilder objCommand = new OdbcCommandBuilder(tempAP);
tempAP.Fill(ds,"Table");
try
{
this._objConn.Open();
byte [] buffer = (byte [])ds.Tables["Table"].Rows[imageNumber]["Data"];
return buffer;
}
catch{this._objConn.Close();return null;}
finally{this._objConn.Close();}
}
Courtesy:
http://www.codeproject.com/Articles/6750/Storing-Images-in-MySQL-using-ASP-NET
For physical drive
http://www.codeproject.com/Articles/2113/C-Photo-Album-Viewer
I have a database with a table "product" in it and in this table there as a field called "PackingPicture" od type Image. I have a form in which I load a record details including the image.
Is there a way to also load the image file path to a textbox?
The reason I want to do this is to that I want to be able to updte the record using sql update query in this form. I wnat to user to be able to update any data filed in this form whether it's the image or not. Is there a way to get the file path upon retrieving the image from the database?
alternatively, if there is a way to save the picture itself without the file path I would be pleased to know.
My code for retrieving data:
public void getData(string brand, string product)
{
DataTable dt = new DataTable();
Connection c = new Connection();
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM tblProduct WHERE productNumber = #Product and brandNumber=#brand", c.con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
c.con.Open();
sqlCmd.Parameters.AddWithValue("#brand", brand);
sqlCmd.Parameters.AddWithValue("#Product", product);
sqlDa.Fill(dt);
SqlDataReader dr = sqlCmd.ExecuteReader();
if (dt.Rows.Count > 0)
{
comboBox2.Text = dt.Rows[0][0].ToString();
//Where ColumnName is the Field from the DB that you want to display
textBox1.Text = dt.Rows[0][1].ToString();
textBox2.Text = dt.Rows[0][2].ToString();
}
while (dr.Read())
{
byte[] img = (byte[])(dr["PackingPicture"]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream stream = new MemoryStream(img);
pictureBox1.Image = System.Drawing.Image.FromStream(stream);
}
}
c.con.Close();
}
Is there a way to get the file path upon retrieving the image from the
database?
If you haven't saved the file path, you cannot retrieve what is not present.
Alternatively, if there is a way to save the picture itself without
the file path
after assigning to the picturebox, you can save the picture from picture box like
pictureBox1.Image.Save("yourfilepath", yourformat);
or you can save it through the stream
using(MemoryStream stream = new MemoryStream(img))
{
FileStream fs = File.OpenWrite("yourfile");
fs.Write(stream.ToArray());
fs.Close();
}
There is no file path because the image exists in memory and in the database, but not in any particular image file. Therefore you need to save it, which you can do like this:
pictureBox1.Image.Save("c:\\path\\to\\image.gif", ImageFormat.Gif); // you have to know your image format