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.
Related
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.
I would like to extract word documents stored as image type fields in SQL and save each individual document in a local folder. The doc files stored in the image type data in sql, are special encoded OLEObjects.
I am trying with one first but I need to do the same for each record in the table. This is what I have done so far:
Byte[] bytData = null;
string constring = #"mystirngconnection";
SqlCommand command = new SqlCommand(#"SELECT LongDescription FROM SuUserReport
WHERE ProductId = 53 AND UserReportId = 31525");
command.CommandType = CommandType.Text;
SqlConnection myconn = new SqlConnection(constring);
command.Connection = myconn;
myconn.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
bytData = (byte[])dr["LongDescription"];
}
}
if (bytData != null)
{
FileStream fs = new FileStream("C:\\Temp\\Test1.doc",
FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write(bytData, 0, bytData.Length);
fs.Dispose();
}
I basically have two problems:
Reading this type of data it is very slow
Using the code above works for normal word documents however the information in my table has OLEObject encoded information, the code saves a word document but the information is only encoded characters
Previously, these images (word documents) where opened straightaway from SQL when the form was opened using an Access bound object frame linked to the longDescription image type field. The user could edit the document by double clicking on this special frame. The following code opens the document and makes it available to save changes:
With oleLongDescription
.Verb = acOLEVerbOpen 'In a separate window
.Action = acOLEActivate
End With
Could anybody be so kind as to help me out with this, please? I do not mind to use c# or vb as long as it works =).
Here is code that I use to open my blobs. the byte[] myarray is the blob field from the database, the fileext is the extension of the file you are creating and the filename is a name you give it. It deletes any previous file of this name.
public static string Openfilefrombyte(byte[] myarray, string fileext, string filename)
{
Computer myComputer = new Computer();
string filenamef = myComputer.FileSystem.SpecialDirectories.Temp + #"\" + filename + "." + fileext;
if (File.Exists(filenamef))
{
File.Delete(filenamef);
}
//save to file and open
FileStream myfs = new FileStream(filenamef, FileMode.CreateNew);
myfs.Write(myarray, 0, myarray.Length);
myfs.Flush();
myfs.Close();
myfs = null;
Process.Start(filenamef);
return "OK";
}
i basically have two problems:
Reading this type of data it is very slow
Answer : Yes Its Slowly But if You save The Image in sql database as VarBinary it will be Fast .
i am Using OpenFileDialog1 To Bring Image Or what You Want (Rar , Pdf .World ...)
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
Try
T4.Text = OpenFileDialog1.FileName
T5.Text = Path.GetExtension(OpenFileDialog1.FileName)
T7.Text = Path.GetFileNameWithoutExtension(OpenFileDialog1.FileName)
Catch ex As Exception
End Try
End If
Here My Code I used it To Save Data In My Sql database :
Dim SQLCON As New SqlConnection(MyDataBaseCon)
Dim CMD As SqlCommand
Try
CMD = New SqlCommand("Insert Into TBLAtach (ID,AtachName,AtachMain,AtachFile,AtachNM,AtachDT,AtachAdres) Values (#ID,#AtachName,#AtachMain,#AtachFile,#AtachNM,#AtachDT,#AtachAdres)", SQLCON)
SQLCON.Open()
CMD.Parameters.Add(New SqlParameter("#ID", SqlDbType.Int)).Value = Val(T1.Text)
CMD.Parameters.Add(New SqlParameter("#AtachName", SqlDbType.Int)).Value = Val(T2.Text)
CMD.Parameters.Add(New SqlParameter("#AtachMain", SqlDbType.Int)).Value = Val(T3.Text)
Dim FSTream As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Dim BNStream As New BinaryReader(FSTream)
Dim FAttach() As Byte = BNStream.ReadBytes(BNStream.BaseStream.Length)
CMD.Parameters.Add(New SqlParameter("#AtachFile", SqlDbType.VarBinary)).Value = FAttach
CMD.Parameters.Add(New SqlParameter("#AtachNM", SqlDbType.NVarChar, 50)).Value = T5.Text
CMD.Parameters.Add(New SqlParameter("#AtachDT", SqlDbType.NVarChar, 50)).Value = TD1.Text
CMD.Parameters.Add(New SqlParameter("#AtachAdres", SqlDbType.NVarChar, 250)).Value = T7.Text
CMD.ExecuteNonQuery()
SQLCON.Close()
FSTream.Close()
BNStream.Close()
MsgBox("Ok ", MsgBoxStyle.Information)
SearchID()
ClearTxT()
Catch ex As Exception
MsgBox(ex.Message)
SQLCON.Close()
WaitPic.Visible = False
End Try
Using the code above, saves a word document but the information is only encoded characters
Answer : To retrieve Data (Image,Pdf,RAR,...)
i am Using This Code :
Try
ItDataset.Clear()
Flt = "Select ID , AtachAdres + AtachNM AS 'Fname' , AtachFile from TBLAtach where ID = " & T1.Text & ""
ItDataset = GeneralDataManager.InquireData(ItDataset, Flt, "TBLAtach")
If Me.BindingContext(ItDataset, "TBLAtach").Count > 0 Then
Dim FName As String = ItDataset.Tables("TBLAtach").Rows(0).Item("Fname")
Dim FAttach() As Byte = CType(ItDataset.Tables("TBLAtach").Rows(0).Item("AtachFile"), Byte())
Dim FStream As New FileStream(FName.ToString, FileMode.OpenOrCreate, FileAccess.Write)
FStream.Write(FAttach, 0, (FAttach.Length))
Process.Start(FName)
FStream.Close()
End If
WaitPic.Visible = False
Catch ex As Exception
MsgBox(ex.Message)
End Try
And Change Your Connection To Your Data Base Con Connection
i hope this Answer Is Good For You .
Thank You .
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.
I'm trying to read binary data from a SQL Server CE database file.
I tried with this code:
string fileName = "C:\\Users\\Luca\\Desktop\\TestNoah\\TestNoah\\NOAHDatabaseCoreSqlCompact.sdf";
connectionString = string.Format("DataSource='{0}'; Persist Security Info=False", fileName);
using (SqlCeConnection con = new SqlCeConnection(connectionString))
{
con.Open();
using (SqlCeCommand command = new SqlCeCommand("SELECT PublicData FROM Action",con))
{
byte[] barrImg = (byte[])command.ExecuteScalar();
List<byte> test = barrImg.ToList<byte>();
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream("C:\\Users\\Luca\\Desktop\\TestNoah\\TestNoah\\" + strfn + ".jpg" , FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg, 0, barrImg.Length);
fs.Flush();
fs.Close();
}
}
This code creates an image that I can't open. Any ideas? Thanks to all
The code below uses the ExecuteReader instead of ExecuteScalar (which should not be used unless you expect only a single return value from the result set where your SqlCeCommand has a WHERE limited by primary key or you have TOP 1 in your SELECT.
string targetDir = "C:\\Users\\Luca\\Desktop\\TestNoah\\TestNoah\\";
var reader = command.ExecuteReader();
while (reader.Read())
{
byte[] img = (byte[])reader["PublicData"];
string path = System.IO.Path.Combine(targetDir, string.Format("{0}.jpg", DateTime.Now.ToFileTime()));
System.IO.File.WriteAllBytes(path, img);
}
If you still have image corruption issues, I expect it would be your source data record.
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