I'm new here and I've also searched about my problem, but I could manage to solve it.
I would like to save and retrieve images to/from Database(SQL) in C# WPF.
I have to make a project about storing a recipe. A recipe contains a table in the Database with the columns: Id, Name, Image, Content.The Information has to be saved and then the name of the recipe(currently done) and images(here is the problem) has to be displayed in a Grid, (so far i don't need to work with the "content" column from the database. That comes later).
I think that I have succeeded in the saving of image to the database, but I am not completely sure. If the saving of the image to the DB is correct, I need a function to retrieve it.
I would be happy for some help. Many Thanks!
D.Tsvet
Thats a sample of the future end result. The image has to be under the name
// Add recipe Window
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public partial class add_Recipe : Window
{
DataSet ds;
string strName, imageName;
byte[] data;
string FileName;
public add_Recipe()
{
InitializeComponent();
}
// Upload a picture from your device
private void browseButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.Title = "Select a picture";
op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
"JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
"Portable Network Graphic (*.png)|*.png";
if (op.ShowDialog() == true)
{
FileName = op.FileName.ToString();
image_box.Source = new BitmapImage(new Uri(op.FileName));
}
string dbConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\guiProjekte\Stands\Projekt_GUI_200418\Projekt_GUI_20042018\Projekt_GUI_160418\Projekt_GUI\1234\1234\Database.mdf;Integrated Security=True;";
private void saveRecipe_Button(object sender, RoutedEventArgs e)
{
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
string q = "insert into recipes(Name,Image,Content)values('" + textBox_newRecipe.Text.ToString() + "','" + ImageData + "','" + content_box.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
MessageBox.Show("Connection made Successfuly..!");
this.Close();
myRecipes_Window obj_myRecipes_Window = new myRecipes_Window();
obj_myRecipes_Window.Show();
//Retrieve Recipe Window:
public void FillRecipes()
{
int column = 0;
int row = 0;
SqlConnection con = new SqlConnection(dbConnectionString);
con.Open();
String sqlSelectQuery = "SELECT * FROM recipes";
SqlCommand cmd = new SqlCommand(sqlSelectQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if(column < 3)
{
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
else
{
column = 0;
row++;
TextBlock nameTxt = new TextBlock();
nameTxt.Text = (dr["Name"].ToString());
nameTxt.FontSize = 20;
nameTxt.FontWeight = FontWeights.Bold;
Grid.SetColumn(nameTxt, column);
Grid.SetRow(nameTxt, row);
grid_Recipes.Children.Add(nameTxt);
column++;
}
}
}
I made some changes about my post. I'm sorry for the previous unclearness.
Related
i am using secugen fingerprint reader and sdk ...with sdk i am able to scan fingerprint,match,verify and display fingerprint image in pictureBox on runtime.. but not able to save in database.. i trien my on code to save fingerprints in database..
this is insertion code
private void BtnVerify_Click(object sender, EventArgs e)
{
Int32 iError;
bool matched1 = false;
bool matched2 = false;
SGFPMSecurityLevel secu_level;
secu_level = (SGFPMSecurityLevel)comboBoxSecuLevel_V.SelectedIndex;
iError = m_FPM.MatchTemplate(m_RegMin1, m_VrfMin, secu_level, ref matched1);
iError = m_FPM.MatchTemplate(m_RegMin2, m_VrfMin, secu_level, ref matched2);
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
if (matched1 & matched2)
{
StatusBar.Text = "Verification Success";
//string name = "sumi";
SqlConnection con = new SqlConnection("Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string qry = "INSERT into teacher_fingerprint (teacher_id,name,teacher_fingerprints)values (#teacher_id,#name,#teacher_fingerprints)";
SqlCommand cmd = new SqlCommand(qry, con);
MemoryStream stream = new MemoryStream();
pictureBoxV1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
con.Open();
cmd.Parameters.AddWithValue("#teacher_id", comboBox2.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text + " " + textBox3.Text);
//cmd.Parameters.AddWithValue("#teacher_fingerprints", m_VrfMin);
cmd.Parameters.AddWithValue("#teacher_fingerprints",pic);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
StatusBar.Text = "Verification Failed";
}
}
else
DisplayError("MatchTemplate()", iError);
}
and this my DrawImage function
private void DrawImageImg(Byte[] imgData, PictureBox picBox)
{
int colorval;
Bitmap bmp = new Bitmap(m_ImageWidth, m_ImageHeight);
picBox.Image = (Image)bmp;
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
colorval = (int)imgData[(j * m_ImageWidth) + i];
bmp.SetPixel(i, j, Color.FromArgb(colorval, colorval, colorval));
}
}
picBox.Refresh();
}
this my database .. i dont know this fingerprint binary is valid or not?
enter image description here
i tried to select fingerprint data in pictureBox but its not working
it gives out of index error in drawImage function
this is my selection code
m_RegMin5 = new Byte[400];
if (iError == (Int32)SGFPMError.ERROR_NONE)
{
DrawImage(fp_image, pictureBox1);
StatusBar.Text = "Device Message: Finger On";
SqlConnection conn = new SqlConnection(#"Data Source=HP; user=sa; password=Admin1; Initial Catalog=schoolmanagement; Integrated Security=True");
string query = "select teacher_fingerprints from teacher_fingerprint where teacher_id=2 ";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
m_RegMin5 = cmd.ExecuteScalar() as byte[];
DrawImageImg(m_RegMin5,pictureBox2);
}
else
{
DisplayError("GetImage()", iError);
}
I'm trying to make this catalog app that display images with its "title" and "category" but I can't seem to display the image because of an error
on the line that says
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
This is the whole of my code. I need the solution so i can print the image with its corresponding details in a list view. Thank you.
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("Books");
comboBox1.Items.Add("Games");
comboBox1.Items.Add("Music");
}
SqlConnection connection = new SqlConnection("Data Source=DESKTOP-4T5BLQ6\\SQLEXPRESS;Initial Catalog=CatalogDB;Integrated Security=True");
SqlCommand command = new SqlCommand();
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlDataReader dataReader;
DataTable dataTable = new DataTable();
MemoryStream stream1;
byte[] photo_array;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
int i = 0;
MemoryStream stream = new MemoryStream();
command.CommandText = "insert into EntryTable(Title,Category,Image) values('" + textBox1.Text + "','" + comboBox1.Text + "','" + pictureBox1.Image + "')";
pictureBox1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (i > 0)
{
MessageBox.Show("Saved new item in index" + i);
}
connection.Close();
MessageBox.Show("Made New Entry");
showData();
clear();
}
void clear()
{
textBox1.Clear();
pictureBox1.Image = null;
comboBox1.SelectedIndex = -1;
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Images only. |*.jpg; *jpeg; *.png; *.gif; *.bmp;";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
}
private void showData()
{
connection.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(100 , 100);
command.Connection = connection;
command.CommandText = "SELECT * FROM EntryTable";
dataAdapter.SelectCommand = command;
dataTable.Clear();
dataAdapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
connection.Close();
}
}
}
Xoriel,
You need to be more specific about what you are asking on SO. Your original post only indicates that you have and error and that it is holding up your app development (welcome to coding). You don't even tell us what error you are getting.
Now you ask how to implement a try catch? You should do a bit of research on your own. As far as try catch, you can start Here.
Your code indicates a lack of understanding about how windows winforms are instantiated and their sequence of events. To me, this indicates that you will have further problems after this one is fixed, so I will add a try catch to your code. It will write the exception to your console.
foreach (DataRow row in dataTable.Rows)
{
var image_buffer = (byte[])(row["Image"]);
MemoryStream image_stream = new MemoryStream(image_buffer, true);
image_stream.Write(image_buffer, 0, image_buffer.Length);
try
{
images.Images.Add(row["id"].ToString(), new Bitmap(image_stream));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = row["Title"].ToString();
listItem.ImageKey = row["Image"].ToString();
listView1.Items.Add(listItem);
listView1.Items.Add(row["Category"].ToString());
listView1.Items.Add(row["Title"].ToString());
}
Your true issue is the format in which you are storing the image to the database and the way in which you are retrieving it.
Regards,
Marc
I stored a image as a byte[] array as blob datatype in MySQL, but I cant find proper way to read that same picture the other way in my asp.net application in image control. In the table "slike" there are 3 columns - image, imagename, brTablice - I was searching for an answer really long and yet didn't find any answers. Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "Server=localhost;Uid=Aleksa;port=3306;Pwd=pass;Database=projekat_automobili;";
MySqlConnection con = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand("SELECT image from slike where brTablice = 'BG-456-SD'", con);
con.Open();
MySqlDataReader DR1 = cmd.ExecuteReader();
if (DR1.Read())
{
//TextBoxJmbg.Text = DR1.GetString(DR1.GetOrdinal("jmbg"));
//TextBoxIP.Text = DR1.GetString(DR1.GetOrdinal("imeprezime"));
//TextBoxTel.Text = DR1.GetString(DR1.GetOrdinal("tel"));
byte[] imgg = (byte[])(DR1["image"]);
if (imgg == null)
{
MemoryStream mstream = new MemoryStream(imgg);
Image1.ImageUrl = System.Drawing.Image.FromStream(mstream).ToString();
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(imgg);
//Image1.ImageUrl = "";
}
else
{
MemoryStream mstream = new MemoryStream(imgg);
Image1.ImageUrl = System.Drawing.Image.FromStream(mstream).ToString();
}
}
con.Close();
}
this is part of project.
mysql table:
----------------------------
G_Picture| G_Picture_size |
----------------------------
0xsd/s45e| 9000 |
-----------------------------
uint FileSize = _sqldatareader.GetUInt32(_sqldatareader.GetOrdinal("G_Picture_size"));
byte[] rawData = new byte[FileSize];
_sqldatareader.GetBytes(_sqldatareader.GetOrdinal("G_Picture"), 0, rawData, 0, (Int32)FileSize);
MemoryStream ms = new MemoryStream(rawData);
__G_Picture.BackgroundImage = new Bitmap(ms);
Now you a bitmap picture.
hope this work.
I am using asp.net with c# to build website, but now i come into a problem. I insert image with blob type into mysql database but i cannot retrieve it. There is no picturebox layout for web controls. I want to use image.imageURL to display this image. I searched a lot, some recommend use another aspx page, some recommend using ashx, but i cannot find a detailed solution. Here is what i have now:
protected void Button1_Click(object sender, EventArgs e)
{
String myname = Request.QueryString["Name"];
string myConnection = "server=127.0.0.1;uid=root;" + "pwd=81210ZLK;database=database;" + "Allow User Variables=True";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.ConnectionString = myConnection;
MySqlCommand SelectCommand = new MySqlCommand();
string mySQL = "SELECT iddb1,fullname,age,gender,healthrecord,headpicture FROM database.db1 where fullname = #myname ";
SelectCommand.CommandText = mySQL;
SelectCommand.Parameters.AddWithValue("#myname", myname);
SelectCommand.Connection = myConn;
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
Int16 ID = myReader.GetInt16(0);
string FName = myReader.GetString(1);
Int16 FAge = myReader.GetInt16(2);
string FGender = myReader.GetString(3);
string FRecord = myReader.GetString(4);
ShowID.Text = ID.ToString();
ShowName.Text = FName.ToString();
ShowAge.Text = FAge.ToString();
ShowGender.Text = FGender.ToString();
ShowRecord.Text = FRecord.ToString();
byte[] imgg = (byte[])(myReader["headpicture"]);
if (imgg == null)
Image1.ImageUrl = null;
else {
MemoryStream mstream = new MemoryStream(imgg);
// Image1.ImageURL = System.Drawing.Image.FromStream(mstream);
}
}
myConn.Close();
}
catch (Exception ex)
{
MessageBoxShow(this, ex.Message);
}
}
Here come with the problem and i marked it with \\
Try this ,
Image1.ImageURL = "data:image/jpeg;base64,"+Convert.ToBase64String(imgg);
I want to retrieve an image from an Oracle database to an Image control in asp.net. I tried but it's not working.
This is the code used for inserting image into database:
protected void btnUpload_Click(object sender, EventArgs e)
{
int imgLength = 0;
string imgContentType = null;
string imgFileName = null;
Stream imgStream = FileUpload.PostedFile.InputStream;
imgLength = FileUpload.PostedFile.ContentLength;
imgContentType = FileUpload.PostedFile.ContentType;
imgFileName = FileUpload.PostedFile.FileName;
if (imgContentType == "image/jpeg" || imgContentType == "image/gif" ||
imgContentType == "image/pjpeg"
|| imgContentType == "image/bmp")
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
FileStream fls;
fls = new FileStream(#imgFileName, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
string query = "insert into image(id,name,photo) values(1,'" + imgFileName + "'," + " :BlobParameter )";
// Establish a new OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.CommandText = query;
cmd.Connection = DbConnection;
cmd.CommandType = CommandType.Text;
System.Data.OracleClient.OracleParameter paramImage = new System.Data.OracleClient.OracleParameter("image",
Oracle.DataAccess.Client.OracleDbType.Blob);
paramImage.ParameterName = "BlobParameter";
paramImage.Value = blob;
paramImage.Direction = ParameterDirection.Input;
cmd.Parameters.Add(paramImage);
cmd.ExecuteNonQuery();
}
Table:
Id Name Photo
1 C:\\user\pictures\animal.jpeg (BLOB)
Below is the code used to retrieve the image into an image control but this code is not working.
For the past two days I've been struggling with this
void GetImagesFromDatabase()
{
try
{
OracleConnection DbConnection = new OracleConnection(con1);
DbConnection.Open();
OracleCommand cmd = new OracleCommand("Select name,photo from Image", DbConnection);
OracleDataReader oda = cmd.ExecuteReader();
while (oda.Read())
{
string path = oda[0].ToString();
img.ImageUrl = path;
if(oda.GetValue(1).ToString() !=""){
FileStream fls;
fls = new FileStream(#path, FileMode.Open, FileAccess.Read);
byte[] blob = new byte[fls.Length];
fls.Read(blob, 0, System.Convert.ToInt32(fls.Length));
fls.Close();
MemoryStream memStream = new MemoryStream(blob);
img.ImageUrl = oda[2].ToString();
}
}
}
catch (Exception ex)
{
}
}
Any ideas? Thanks in advance
maybe this code can help you:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}