C# getting file path of an Image in an imagebox - c#

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

Related

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

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 !";
}}

Saving and retrving image from mysql

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

Match bitmap image from server via BiometricSDK with another bitmap image?

I have stored a bitmap image in a server and want to do matching through BiometricSDK with another image that I select. I have got no idea how to solve it. Here is my current code.
//Make finger print image get through SDK process
Boolean result = true;
var fprintsdk = new BiometricsSDK.FingerPrint.CFingerPrint();
var fprintresult = new BiometricsSDK.FingerPrint.CFingerPrint();
//get finger print image
fprintsdk.setFingerPrintImage(fprintsdk.getFingerPrintImage());
fprintresult.setFingerPrintImage(fprintresult.getFingerPrintImage());
FPrintImg.Image = fprintresult.getFingerPrintImageDetail();
FPrintImg.SizeMode = PictureBoxSizeMode.StretchImage;
//Open window to select finger print image
var open = new OpenFileDialog();
open.FileName = string.Empty;
open.Filter = "BMP|*.bmp"; //open text file as default
open.Multiselect = false;
if (open.ShowDialog() == DialogResult.OK)
{
Bitmap bmp = (Bitmap) Image.FromFile(open.FileName); //select image and store out
string Constr = "Provider=Microsoft.JET.OLEDB.4.0;Data Source = BankServer.mdb";
OleDbConnection Conn = new OleDbConnection(Constr);
Conn.Open();
string sFingerPrint = "Select * from Server Where Hash = '" + ccinfo + "'"; //get data from server
OleDbCommand cmd1 = new OleDbCommand(sFingerPrint, Conn);
OleDbDataReader read1 = cmd1.ExecuteReader();
while (read1.Read()) //loop all data
{
//(Problem Stuck over Here)
if (read1["FingerPrint"].GetType() == bmp) //Comparison text file and database
{
Messagebox.show("Well Done");
}
}
}
I don`t know what SDK you are using. Therefore, you needs to search how to generate a template from this two images and match the two templates. Biometric match is not done with images directly but with templates.
If you tell us what SDK you are using maybe I can answer it better.

Categories

Resources