Load an image to C# and then inserting into MySQL table - c#

Here's what I need: I'm making a software for inventory control, but I have to upload an image of the product among the data. I'm working with C# and MySQL.
I do not know how to put the image loaded into the pictureBox to a MySQL table.
Any ideas? I'm completely lost here.
I loaded the image into a pictureBox using this code:
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "All Files (*.*)|*.*";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
How do I insert the loaded image into a MySQL table? I suppose that the image attribute in the table should be:
`img` LONGBLOB NOT NULL
And then, how do I call back the image to a pictureBox from MySQL? I suppose (again) that the query it is something like:
select img from table_name where id = '';
Finally, when I have the query, how do I load the image to a pictureBox from MySQL?
Thank you very much.

I will offer two solutions. The first solution is to store the raw image in bytes in the database directly. The second solution is what I personally recommend - which is to instead use the path of the image file in the database instead.
Here an excerpt from an article which brings up some excellent points on whether or not to BLOB.
Well, there are several reasons why you should not store binary data
in your database:
The whole point of storing data in a SQL database, is to put some kind of ordering and structure on your data, as well as being able to
search on these data. But how do you search in the binary data of a
picture?
For large data sets, storing binary data will quickly run up the size of your database files, making it harder to control the size of
the database.
In order to store binary data in the database, you must continually escape and unescape the data to ensure that nothing breaks.
Storing images on the file system has a marginally faster retrieval rate. Now here are some reasons why you should:
There is one good reason why you might want to store the binary data
in the database:
Replication. Storing images in a database allows for all of your data to be central stored which is more portable, and easy to
replicate.
Here is how you would go about choosing your image file:
using (var openFileDialog = new OpenFileDialog())
{
openFileDialog.Title = "Choose Image File";
openFileDialog.InitialDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
openFileDialog.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog.FileName);
}
// store file path in some field or textbox...
textBox1.Text = openFileDialog.FileName;
}
Solution 1: BLOB approach
// Write to database like this - image is LONGBLOB type
string sql = "INSERT INTO imagetable (image) VALUES (#file)";
// remember 'using' statements to efficiently release unmanaged resources
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand(sql, conn))
{
// parameterize query to safeguard against sql injection attacks, etc.
cmd.Parameters.AddWithValue("#file", File.ReadAllBytes(textBox1.Text));
cmd.ExecuteNonQuery();
}
}
// read image from database like this
string sql = "SELECT image FROM imagetable WHERE ID = #ID";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", myInt);
byte[] bytes = (byte[])cmd.ExecuteScalar();
using (var byteStream = new MemoryStream(bytes))
{
pictureBox1.Image = new Bitmap(byteStream);
}
}
}
Solution 2: Storing Path of File on Filesystem
// Some file movement to the desired project folder
string fileName = Path.GetFileName(this.textBox1.Text);
string projectFilePath = Path.Combine(projectDir, fileName);
File.Copy(this.textBox1.Text, projectFilePath);
// Write to database like this - imagepath is VARCHAR type
string sql = "INSERT INTO imagepathtable (imagepath) VALUES (#filepath)";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#filepath", projectFilePath);
cmd.ExecuteNonQuery();
}
}
// read from database like this
string sql = "SELECT imagepath FROM imagepathtable WHERE ID = #ID";
using (var conn = new MySqlConnection(cs))
{
conn.Open();
using (var cmd = new MySqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#ID", myInt);
pictureBox1.Image = new Bitmap(cmd.ExecuteScalar().ToString());
}
}

Related

Database varbinary(MAX) to RichText Box

Here i Saved .Doc files in Database and i used varbinary(MAX) Datatype. Now I want to bind the varbinary(MAX) field to Richtext box, Here i am used bellow code to Read binary format data to string type.
string Query = "Select Name, ContentType, DocFileText from <TableNAme> where Id=5";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
SqlDataReader sqlRead = cmd.ExecuteReader();
while (sqlRead.Read())
{
byte[] fileData = ((byte[])sqlRead["DocFileText"]);
Richtextbox1.Text = Encoding.ASCII.GetString(fileData);
}
but the data should be in unreadable format like :
PK!0?(r?[Content_Types].xml ?(??T?n?0?W??D?V??????[??0??z??l?I?Q?B? \"%?????????l ?w%?=???^i7+???%?g&??0?A?6?l4??L60#????S ????X??&??V$z?3??3 ??????%p)O5?????5}?:?`?e????V?DFK??)_:?K%?)?l??\?!??U?'?v?7?&j?X??*,??+W^.,???????W????k??D?????X?????>??N!??FZ??&0m??ly??)?q?9??d}???#??????????R??/??s???*&:t??g?????????8Y?O?[??&V0}?X????????>?#??;?F?io.????PK!???N_rels/.rels ?(????JA???a?}7? "???H?w"????w?????? ?P?^????O?????;?<?aY????`G?kxm??PY?[??g G??ino?/"f3??\???T??I S??????????W????Y ig?#??X6_?]7~ f?????ao?.b*lI?r?j)?,l0?%??b? 6?i???D?_???, ? ???|u?Z^t??y??;!Y,}{?C??/h>??PK!??? ?word/_rels/document.xml.rels ?(????J?0?????n????l?????v???$?j?????..??K`?????0??L'????YI?#[????????? D mK?9? ?Ooovo?i?G?i? ?? Q?,e(4:D?G?7??F????.>u?r?[???^x?C???{??s??????_\q4h?J?H?????FRpR"?ya?* ?p???d?x{49z??Dp?? ?kB?Nc)?3Ybx\??r?2?w3?????&?7??Vr&?#??oK??PK!??????2word/document.xml?Y[O?0~????r????BiCH????.???????_?s?84?-a-#??;>??|>N..??P?S.?u???5{l??}???{??5!I??#???Z#sl?}?????M??iuK??B?? ???]????=???O?F??o????ba?)??Nw8,Ht'pn6??P7??p)N?*97?tl???#'L???????se~??;?Y??;???}?K?????v???M??????K???j?>U????+g?^U|?????C N???M?~%????a???????H??m?/?&?M_?i=??????VQN?0?J?#??l??J?|!U??4[]S%??7?$?i7:?bB???Nl??{uH5""3%hA?:?g?????n???:????#??xi%?z_vZ?*U?m??u??2?Jq??'?3?h???1Q?, ??????'??;??g?? ?Ev?????0$??`XmtGr??!?e_?}v??#??????????dT?h+?j-,A?%#???6? ??w?????|UOQ4????E?ga?V???#?????w2?|????????~????WH??X????t?^^???O????????lK?=?K????? ?93?.????????????ev?j??????|?4?y0??e?????=FV ??^?r?Zh9#??_vvsN3?r????????\m?]??1Y n4?X/2?.??`?%O?a????A??l??????N?d???????PK!?????Pword/theme/theme1.xml?YOo?6??w toc'vu????-M?n?i???P?#?I}?????a??m?a[????4?:l???GR??X^?6???>$?????????!)O?^?r?C$?y#?????/?yH*??????)?????????UDb?`}"?q???J?????X^?)I`n?E???p)???li?V[]?1M???G?M?Ge???D?????3Vq%'#q??????$?8??K?????)f?w9:????? x}r?x????w???r?:\TZaG?*?y8I?j?bR??c|X??????I u3KG?nD1?NIB?s??? ??R??u???K>V?.EL+M2?#'?f??i~?V??vl?{u8??z??H? ?*????:?(W???? ~??J??T?e\O*?tHG??HY???}KN??P?*???????T???9/#??A7?qZ??$*c????qU??n??w?N??%??O??i??4=3??P?? ????1?P?m\\9?????????M???2a?D?]?;Yt?\????[x??????]?}Wr??|?]??g-??? eW? ?)6-r??CS?j?? i?d ?D??A???IqbJ#x????6k???#??A?Sh???&??t(Q?%??p%m??&]?caSl=?X???????\P?1?Mh?9?M???V?dDA??aV?B??[??fJ???P|8???A?V^???f ?H??n???-??"??d>?z???n????? ?????>??b???&?????2??v????Ky?????D:????,AGm??\nz??i?????.u??YC?6?OMf??3o?r??$??5?????NH?T[XF64?T,?????M0?E)`#?5?XY?`???;??%?1?U???m;???R>QD????D?cp?U?'??&LE?/p???m????%]?????8fi??r?S4?d7y\?`?J??n??????I?R???3U?~7+?????#??m?q?BiD??????????i*?L6?9??m?Y&?????i???HE??=(K&?N!V??.K?e?LD????{D ????vE???de??N????e?(?MN9??R??6????&3(??a????/D??U?z???)???D????_??k??wXXub?????(?9??8?????????????<4??u?>?p?? ???F????
Here i used
Encoding.UTF8.GetString(fileData);
Encoding.Unicode.GetString(fileData);
but these are also not working.
How can i read Doc file from database to richtextbox ?
And My Uploaded Code is:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
Stream str = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(str);
Byte[] size = br.ReadBytes((int) str.Length);
using (SqlConnection con = new SqlConnection(Connstring))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "insert into Gtrans(Name, ContentType, DocFileText) values(#Name, #ContentType, #DocFileText)";
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", "application/word");
cmd.Parameters.AddWithValue("#DocFileText", size);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Okay there are two problems with your approach.
Point 1 (If you are using winforms):
If you like to load rtf text into a RichTextBox then you have to use the Rtf property of the RichTextBox. Not the Text property. See this for more information.
Point 2:
You can't open .doc in rtf just by passing the .doc string to rtf. .doc is something other that rtf.
The good news: it is possible, the bad: you need MS Word.
Add reference to "Microsoft Word 15.0 Object Library" is under the 'Com' section of the references window
Use this code to convert the doc file to rtf file
.
byte[] yourDocData = null; // in your case (byte[])sqlRead["DocFileText"]
// Save your data as file so word can read it
var tmpFile = Path.GetTempFileName();
using (var fileStream = new FileStream(tmpFile, FileMode.Append, FileAccess.Write))
using (var writer = new BinaryWriter(fileStream)) {
writer.Write(yourDocData);
}
// Convert .doc to .rtf
var newWordFile = (object) tmpFile;
var newRtfFile = (object) Path.GetTempFileName();
var wordObject = new Microsoft.Office.Interop.Word.Application();
var docs = wordObject.Documents.Open(ref newWordFile);
docs.SaveAs(ref newRtfFile, WdSaveFormat.wdFormatRTF);
// This is your rtf code
var yourRtfCode = File.ReadAllText(newRtfFile.ToString());
// Dispose
docs.Close();
wordObject.Quit();
source
Important
Use the same Encoding for saving / loading your .doc from the database!
Set the yourRtfCode not to the text-property of your control but to the property accepting rtf-text

Download File from BLOB Oracle using c#

i have created simple project in c# to save file data into Oracle Database using BLOB data type and it worked. i used devexpress gridcontrol to show the data. This is the sample data that i have created.
in the btnDownload will download data from blob oracle that i selected row. here is my code:
var rowHandle = gridView1.FocusedRowHandle;
var obj = gridView1.GetRowCellValue(rowHandle, "FILENAME");
if(koneksidb.con.State == ConnectionState.Open)
{
koneksidb.con.Close();
}
koneksidb.con.Open();
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT * FROM LATIHANFILEMANAGER WHERE FILENAME='"+ obj +"'";
cmd.Connection = koneksidb.con;
dr = cmd.ExecuteReader();
while(dr.Read())
{
UInt32 FileSize = Convert.ToUInt32(dr.GetInt32(dr.GetOrdinal("FILESIZE"))); //get file size from table LATIHANFILEMANAGER
rawData = new byte[FileSize];
var nilai = dr.GetBytes(dr.GetOrdinal("FILEDATA"), 0, rawData, 0, (int)FileSize); //this file that i wanna download
FileStream fls = new FileStream(#"D:\newfile.png", FileMode.OpenOrCreate, FileAccess.Write);
fls.Write(rawData, 0, (int)FileSize);
fls.Close();
}
dr.Close();
when i run this project and download the image, i got a file and file size but it cannot be opened.
here is the file that i captured:
this tutorial i got from this link:
https://docs.oracle.com/cd/E17952_01/connector-net-en/connector-net-programming-blob-reading.html
any suggest?
first, you show your Image(BLOB) from database to PictureBox, than use SaveFileDialog.
for more information visit
How to use saveFileDialog for saving images in C#?

populate list with images from database

I want to retrieve the images from SQL table and save it in the list and show it in my listview. But I don't know how to do this. I need your help.
I am using SQL Server 2008, Visual Studio 2008, C# Window Application.
Here is my code:
cmd = new SqlCommand("Select ScanImage from ScanDocuments", con);
dr = cmd.ExecuteReader();
List<ImageList> lstitem = new List<ImageList>();
while (dr.Read())
{
ImageList _image = new ImageList();
byte[] data = (byte[])dr["ScanImage"];
MemoryStream ms = new MemoryStream(data);
Image bmp = new Bitmap(ms);
lstitem.Add(bmp);
}
Your code has several flaws - you need to use something like this instead:
// define connection string and select statement
// I used AdventureWorks 2012 database - change to match *YOUR* environment
string connectionString = "server=.;database=AdventureWorks2012;integrated security=SSPI;";
string query = "SELECT ThumbNailPhoto FROM Production.ProductPhoto";
// define a list of "Image" objects
List<Image> listOfImages = new List<Image>();
// using the SqlConnection and SqlCommand ....
using(SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
// open connection
conn.Open();
// execute SqlCommand to return a SqlDataReader
using (SqlDataReader rdr = selectCmd.ExecuteReader())
{
// iterate over the reader
while (rdr.Read())
{
// load the bytes from the database that represent your image
var imageBytes = (byte[]) rdr[0];
// put those bytes into a memory stream and "rewind" the memory stream
MemoryStream memStm = new MemoryStream(imageBytes);
memStm.Seek(0, SeekOrigin.Begin);
// create an "Image" from that memory stream
Image image = Image.FromStream(memStm);
// add image to list
listOfImages.Add(image);
}
}
conn.Close();
}
This works just fine for me - it loads the 101 ThumbNailPhoto from the AdventureWorks2012 database

How to use Microsoft Access Database's Attachment Data Type?

I'm trying to use Microsoft access database's attachment data type.
but i don't know how to use it.
I want to insert image into access database using .Net Windows Form.
In SQL Server 2008 Image data type and byte is compatibility for that.
but i don't know how to insert image into access database.
is there need to change byte like SQL Server or can directly insert into access database.
using (var connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\BlankDatabase.mdb"))
{
connection.Open();
// Create table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
CREATE TABLE FileTable (
FileName VARCHAR(255),
File IMAGE)
";
command.ExecuteNonQuery();
}
var imageContent = File.ReadAllBytes(#"C:\logo.png");
// upload image to the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
INSERT INTO FileTable (FileName, File)
VALUES (#FileName, #File)
";
command.Parameters.AddWithValue("#FileName", "Logo");
command.Parameters.AddWithValue("#File", imageContent);
command.ExecuteNonQuery();
}
// retreive image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
SELECT File
FROM FileTable
WHERE FileName = 'Logo'
";
var readImageContent = (byte[])command.ExecuteScalar();
File.WriteAllBytes(#"C:\logo1.png", readImageContent);
}
// alter image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
UPDATE FileTable
SET File = #File
WHERE FileName = 'Logo'
";
command.Parameters.AddWithValue("#File", imageContent);
command.ExecuteNonQuery();
}
// delete image from the table
using (var command = connection.CreateCommand())
{
command.CommandText = #"
DELETE FROM FileTable
WHERE FileName = 'Logo'
";
command.ExecuteNonQuery();
}
}
In this code BlankDatabase.mdb is an empty MS Access database file.
[Edit]
When you saved image to the database, as shown above you can retrieve image bytes as shown above:
You can construct Image from image bytes like this:
var imageConverter = new ImageConverter();
pictureBox1.Image = (Image)imageConverter.ConvertFrom(fileContent);
Here is what I use to get the file attachments from an OleDB connection in .net code to a microsoft access database with attachment field types:
This method gets the file you want in Ordinal Position from the attachment field name "Pic" in my table.. you can store many files in the attachment field, so you have to specify which of the files you want.. hope this helps ( i use this as web url to take the image from the attachment field in the access database, but the COM calls will be the same in your winform app)..good luck
try
{
//You get your file in a byteArray fileType is just the ordinal file position in the fileattachment field..ex. 1, 2, 3 (shown in the access listbox)
Response.BinaryWrite(GetPicField(productID, fileType));
Response.ContentType = "image/bmp";
}
catch
{
//need to get missing product photo image here as well N/A
Response.BinaryWrite(GetNA_Image());
Response.ContentType = "image/bmp";
}
//getting from Database
private byte[] GetPicField(string productID,int fileToShow)
{
DBEngine dbe = new DBEngine();
Database db;
Recordset rs;
byte[] byteArray = null;
dbe = new DBEngine();
db = dbe.OpenDatabase(Application["DB_FileName"].ToString());
rs = db.OpenRecordset("SELECT PIC FROM PRODUCT WHERE PRODUCTID = " + productID, RecordsetTypeEnum.dbOpenForwardOnly, 0, LockTypeEnum.dbPessimistic);
if (rs.RecordCount > 0)
{
Recordset rs2 = (Recordset2)rs.Fields["Pic"].Value;
int i = 1;
while (i < fileToShow)
{
rs2.MoveNext();
i++;
}
//get the thubmnail
Field2 f2 = (Field2)rs2.Fields["FileData"]; //0 is first pic
byteArray = f2.GetChunk(20, f2.FieldSize - 20);
System.Runtime.InteropServices.Marshal.ReleaseComObject(f2);
rs2.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rs2);
f2 = null;
rs2 = null;
}
rs.Close();
db.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(rs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(dbe);
System.Runtime.InteropServices.Marshal.ReleaseComObject(db);
rs = null;
db = null;
dbe = null;
return byteArray;
}

How do I store a image BLOB in an access database after getting the name from openfiledialog?

I am developing a C# application that has an Access database. What I want to do is allow a user to select an image through an "openfiledialog." I then want to store the image in one of the table of the access database in a BLOB field. I have searched over the internet, but found nothing helpful. I hope you can help me.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
// textBox1.Show(openFileDialog1.FileName.ToString());
// MessageBox.Show(openFileDialog1.FileName.ToString());
textBox1.Text = openFileDialog1.FileName.ToString();
String filename = openFileDialog1.FileName.ToString();
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Policias.accdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO DetallesMunicipio(imagen) VALUES (#imagen)";
cmd.Parameters.AddWithValue("#imagen", buffer);
conn.Open();
cmd.ExecuteNonQuery();
}
}
else
{
MessageBox.Show("Porfavor selecciona una imagen");
}
}
but now how can I be sure that is stored in the access database?
Example:
string filename = "foo.txt"; // TODO: fetch from file dialog
byte[] buffer = File.ReadAllBytes(filename);
using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=foo.mdb"))
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO MyTable VALUES (#Name, #Data)";
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#Data", buffer);
cmd.ExecuteNonQuery();
}
What you will want to do is something similar to the following.
using (OpenFileDialog fileDialog = new OpenFileDialog){
if(fileDialog.ShowDialog == DialogResult.OK){
using (System.IO.FileInfo fileToSave = new System.IO.FileInfo(fileDialog.FilePath)){
MemoryStream ms = System.IO.FileStream(fileToSave.FullNae, IO.FileMode.Open);
//Here you can copy the ms over to a byte array to save into your blob in your database.
}
}
}
I would use File.ReeadAllBytes(file) and save the byte[] there in the DB.

Categories