How to retrieve image from mysql database? - c#

I have stored image into mysql using following and now i want to retrieve... I want to convert ny image from bytes to image and then display it ... how can i do that
public void LoadImages()
{
byte[] ImageData;
string image = txtLogo.Text;
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = BitConverter.GetBytes(fs.Length);
string query = "insert into Fn_Pictures(Images,Email)values(#Images,'" + txtEmailId.Text + "')";
MySqlConnection con = new MySqlConnection(connstring);
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader myReaeder;
con.Open();
myReaeder = cmd.ExecuteReader();
}

It's a complete overhead to store images in a database.
Just save them on the disk, it's a lot faster.
If you want to store them use blob, and you will need a different page for the image, with the right headers to display it.

In order to store images , store on disk
All you has to do is save the image path in Database or just image name and through dynamic coding you can retrieve absolute path of image , This would be much more faster , irespective of any technology

Related

C# SQL to get a picture from the database

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.

How to convert Blob value to Image

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

How can I display my picture in postgres database with c#?

I can save in my postgres databes my picture which is in picturebox.
but after How can I display my picture in postres database with c# ?
FileStream fs = new FileStream(resimPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] resim = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
PostgisBaglan.Open();
strEksenCizgisiUpdate = "INSERT INTO reismDatabase(resimismi,resimkendi) values('resim3','"+resim+"');";
NpgsqlCommand EksenCizgisiUpdateCommand = new NpgsqlCommand(strEksenCizgisiUpdate, PostgisBaglan);
EksenCizgisiUpdateCommand.ExecuteNonQuery();
PostgisBaglan.Close();
openFileDialog1.Filter = "Jpeg Dosyası (*.jpg)|*.jpg|Gif Dosyası (*.gif)|*.gif|Png Dosyası (*.png)|*.png|Tif Dosyası (*.tif)|*.tif";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
resimPath = openFileDialog1.FileName.ToString();
}
You can't display an image "from the database".
In your application, you need to read the image from the database, and then display it.
Assuming your table looks like this:
create table reismDatabase (
resimismi text, -- or some variant
resimkendi bytea
);
This would be code to read the table contents into a picture object:
NpgSqlCommand cmd = new NpgsqlCommand("select resimismi, resimkendi from reismDatabase",
conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string photoName = reader.GetString(0);
Byte[] photoContents = (Byte[])Reader.GetValue(1);
Image photo;
if (photoContents != null)
{
using (Stream st = new System.IO.MemoryStream(photoContents))
photo = Image.FromStream(st);
}
}
reader.Close();
From there, you can assign photo to your pictureBox.Image.
I found my solution.
Postgisconn.Open();
str= "INSERT INTO testimage (id, image) VALUES (1, lo_import('C://test.jpg'));";
NpgsqlCommand cmmnd= new NpgsqlCommand(str, Postgisconn);
cmmnd.ExecuteNonQuery();
Postgisconn.Close();
I save with this query my image in my database.
pictureBox1.Image.Dispose();
Postgisconn.Open();
str= "SELECT lo_export(testimage.image, 'C://outputimage.jpg') FROM testimage WHERE id =1;";
NpgsqlCommand cmmnd= new NpgsqlCommand(str, Postgisconn);
cmmnd.ExecuteNonQuery();
Postgisconn.Close();.
pictureBox1.Image = Image.FromFile("C://outputimage.jpg");
with this query , I display my database image to picturebox.
Thank all of you who answer to my question.

Issue while inserting images to the mysql database

I am trying to insert an image from windows application to mysql database , it has been executed succesfully but there exists no data in my table.
Here I have used the following code. The execution is successful, according to my table email id and image must must be stored in table , but both the fields are saved as empty.
public void LoadImages()
{
MySqlConnection cn = new MySqlConnection(connstring);
cn.Open();
string image = txtLogo.Text;
byte[] ImageData;
FileStream fs = new FileStream(image, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
ImageData = BitConverter.GetBytes(fs.Length);
br.Close();
fs.Close();
MySqlParameter parImage = new MySqlParameter();
parImage.ParameterName = "?Images";
MySqlCommand cmd = new MySqlCommand("insert into Fn_Pictures(Images,Email)values(?Images,'" + txtEmailIdText + "')", cn);
parImage.MySqlDbType = MySqlDbType.MediumBlob;
parImage.Size = 3000000;
parImage.Value = ImageData;//here you should put your byte []
cmd.Parameters.Add(parImage);
cmd.ExecuteNonQuery();
cn.Close();
}
BitConverter.GetBytes(fs.Length);
This returns the length as a byte[4], not reads the image data.
Take a look here for reading the file:
http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes(v=vs.110).aspx
You probably also want to set parImage.Size to ImageData.length, not 3000000.

C# getting file path of an Image in an imagebox

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

Categories

Resources