How to convert Blob value to Image - c#

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

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.

Converting image from database in C#

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.

Saving multiple Images at once to the database with a FileUpload Control

I am working on a company Blog site, and when a user is making a post, they can add an image from their computer to the post. I used a FileUpload control to do this, and it works great. However, I am trying to change the functionality to allow the user to select and upload multiple images in one post, and I am running into some issues. I have set the 'allow multiple' property to 'true', however once multiple images are selected into the control (Image URLs get separated by a comma) and the post button is clicked, only one of the images is inserted into the database, but it is inserted as many times as images there are, and only that one image is displayed on the blog post. So if I try to add three different images, it inserts three instances of the first image into the database. The code corresponding to the the FileUpload in my onClick function is below:
if (imageUpload.HasFile == true)
{
SqlCommand maxMessId = new SqlCommand("SELECT Max(MessageID) FROM BlogMessages", conn);
lastMessageID = Convert.ToInt32(maxMessId.ExecuteScalar());
foreach (var uploadedFile in imageUpload.PostedFiles)
{
SqlCommand cmdInsertImage = new SqlCommand("INSERT INTO BlogImages(Image, MessageID) VALUES (#Image, #MessageID)", conn);
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
cmdInsertImage.Parameters.AddWithValue("#MessageID", lastMessageID);
cmdInsertImage.ExecuteNonQuery();
}
}
I am thinking the issue could be with:
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = imageUpload.FileBytes;
If that is getting the file bytes for only one image.. I am not sure how to get the filebytes for both files. The image column in my BlogImages table is of the type Image.
Any suggestions are much appreciated!
Are you sure that you're working on the right way ?????PostesFiles are the list of file and each one has it own properties you need to read from there.....nothing else
Here a simples examples
For Each xx In fp.PostedFiles
xx.InputStream
xx.ContentLength
xx.FileName
Next
Where those properties upon expose Inputstrem a stream of the image,ContenteLenght it lenght, Filename the filename of the images.So when you pass the imageupload.FileBytes is not the correct way to achive your goal.You have to read the stream and return a bytearray to save the data withing your sql server.Nothing else i hope it could help you to solve your issue.
UPDATE*
Assume that you're into the foreach loop for each single file you have to setup its own bytearray
MemoryStream ms = new MemoryStream();
file.PostedFile.InputStream.CopyTo(ms);
var byts = ms.ToArray();
ms.Dispose();
then
change your insert statement like this
cmdInsertImage.Parameters.AddWithValue("#Image", SqlDbType.Image).Value = byts;
not tested but it should solve the issue.
UPDATE 2
if (test.HasFiles) {
StringBuilder sb = new StringBuilder();
foreach (void el_loopVariable in test.PostedFiles) {
el = el_loopVariable;
sb.AppendLine("FILENAME:<B>" + el.FileName.ToString + "</B><BR/>");
MemoryStream ms = new MemoryStream();
el.InputStream.CopyTo(ms);
byte[] byts = ms.ToArray;
ms.Dispose();
sb.AppendLine(string.Join(";", byts));
sb.AppendLine("<br/<br/>");
byts = null;
}
LitResponse.Text = sb.ToString;
}
I think the issue is that in your for each loop, you're stepping through the posted files, but you're still just using ImageUpload.FileBytes each time, which I expect would be returning the same thing each time.
I'm not super familiar with the file upload control, but maybe you can use the ContentLength property of your uploaded file object to index into the byte array returned by ImageUpload.FileBytes (assuming that array contains each of the multiple files).
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strImageName = txtImage.Text.ToString(); //to store image into sql database.
if (FileUpload1.PostedFile != null &&
FileUpload1.PostedFile.FileName != "")
{
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Pictures(ID,ImageName,Image)" +
" VALUES (#ID,#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
//retrieve latest ID from tables which was stored in session.
int ID = Convert.ToInt32(System.Web.HttpContext.Current.Session["ID"].ToString());
SqlParameter ID = new SqlParameter
("#ID", SqlDbType.Int, 5);
ID.Value = (Int32)ID;
cmd.Parameters.Add(ID);
SqlParameter ImageName = new SqlParameter
("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
lblMessage.Text = "File Uploaded";
lblSuccess.Text = "Successful !";
}}

How to retrieve image from mysql database?

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

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