SqlDataAdapter has the .Fill(dataset) function, but SqlDataReader doesn't.
This should extract the image and place it inside my byte[]
while (reader.Read())
{
listOfProfiles.Add(new Profile
{
ProfileImage = (byte[])profileReader["imageFile"]
});
I've tried to create a DataSet and create a row where the image should be
DataSet ds = new DataSet();
byte[] MyData = new byte[0];
DataTable table0 = new DataTable("table0", "table0");
table0.Columns.Add("imageFile"); // DB column name
table0.Rows.Add(listOfProfiles[0].ProfileImage);
ds.Tables.Add(table0);
DataRow myRow;
After the image is in my DataSet, I tried converting it to a BitmapImage, but got the following error:
Unable to cast object of type 'System.String' to type 'System.Byte[]'.'
This is the code that should convert the varbinary image from the database to a BitmapImage:
if (ds.Tables[0].Rows.Count == 1)
{
myRow = ds.Tables[0].Rows[0];
MyData = (byte[])myRow["imageFile"];
MemoryStream stream = new MemoryStream(MyData);
stream.Write(MyData, 0, MyData.Length);
stream.Position = 0;
System.Drawing.Image img =
System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
hpProfileImage.Source = bi;
}
Any help is very appreciated
A working example of loading image from database in WPF
private void LoadLoggedInUsersDetails()
{
con.Open();
SqlCommand cmd2 = new SqlCommand("Select * from userinfo where ID='" + idStringHere + "'", con);
byte[] photo;
SqlDataReader dr2 = cmd2.ExecuteReader;
while (dr2.Read)
{
photo = (byte[])dr2(11);
MemoryStream strm = new MemoryStream(photo);
BitmapImage bi = new BitmapImage;
bi.BeginInit();
strm.Seek(0, SeekOrigin.Begin);
bi.StreamSource = strm;
bi.EndInit();
imageControl.ImageSource = bi;
}
con.Close();
}
A quick explanation : First i am declaring a byte[] variable.Then,as the SqlDatareader starts to read data from the database,the byte[] variable gets it's value from the datareader's specific column/cell.Then i declare a MemoryStream which reads the byte[].Now we declare a BitmapImage variable.BeginInIt and EndInIt are essential in this case.To make sure the Memorystream's position is at the beginning,we use strm.Seek(0, SeekOrigin.Begin).The bitmapImage uses that MemoryStream as a StreamSource.Finally we call EndInIt and do whatever we want to do with the bitmap , in this case,use it as a ImageBrush's ImageSource
Related
I am able to download (retrieve) image from Mysql Database in WPF in C# by this piece of code.
This code i have copy from this https://www.experts-exchange.com/questions/25096053/Retrieve-images-in-C-WPF-Application-from-SQL-Server-Database.html
Website.
But i don't know how this code work line by line. If anyone who have knowledge about this please help.
Code is here.
string query = "SELECT image_data from image_table WHERE image_id=22";
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Byte[] bindata = (Byte[])dataReader["image_data"];
MemoryStream strm = new MemoryStream();
strm.Write(bindata, 0, bindata.Length);
strm.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
download.Source = bi;
}
i am able to retrieve image from database in wpf in c# with this code. The only problem with this code is it retrieve only one image ata a time. Before using this code add System.Drawing.Imaging. library in your code.
BitmapImage bi = new BitmapImage();
System.Drawing.Image img;
MemoryStream strm = new MemoryStream();
strm.Write(bindata, 0, bindata.Length);
strm.Position = 0;
img = System.Drawing.Image.FromStream(strm);
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
I know this question has been asked many times, but my problem is not being solved.
I inserted image to database and data type of my field is image. But I am trying to display the image in picture box this exception occurs.
Parameter is not valid.
Here is my code:
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] Img = (byte[])dr["imgImage"];
MemoryStream MS = new MemoryStream(Img);
MS.Seek(0, SeekOrigin.Begin);
//System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
//System.Drawing.Image img = (System.Drawing.Image)converter.ConvertFrom(Img);
pictureBox1.Image = Image.FromStream(MS);
}
i guess it works.
PCT.Image= Image.FromStream(ms);
is that works?
edit1:
////sql connection codes here
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] picture = (byte[])dr[0];
MemoryStream ms = new MemoryStream(picture, 0, picture.Length);
ms.Write(picture, 0, picture.Length);
RegPicture = Image.FromStream(ms, true);
pictureBox1.Image = RegPicture;
}
////sql connection codes here
I am using the following function to store image in db
void SaveImage(byte[] image)
{
MySqlConnection con = new MySqlConnection(db);//new connection is made
con.Open();
string cmdText = "INSERT INTO Picture(RoomNo ,pic )VALUES ('" + RoomNo.Text + "',?Image)";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
cmd.Parameters.Add("?Image", image);
cmd.ExecuteNonQuery();
}
In main I am calling the function like this
using (var ms = new MemoryStream())
{
picbox.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
SaveImage(ms.ToArray());
}
I do not know how to display it in a picture box .. can any one help me???
Are you using Windows Forms? And you must Convert Byte array to Image for displaying it in Picture Box.
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
And how did you convert Image to byte array. I hope that problem not there. You can use:
private byte[] ImageToByteArray(string ImageFile)
{
FileStream stream = new FileStream(
ImageFile, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream);
// Convert image to byte array.
byte[] photo = reader.ReadBytes((int)stream.Length);
return photo;
}
set your image picture box using Image method (FromStream)
yourPictureBox.Image = Image.FromStream(ms);
For Save Image I am try this code.
MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
mycon.Open()
FileStream fs = new FileStream("b.jpg", FileMode.Open, FileAccess.Read);
int sizee = (int)fs.Length;
byte[] rawData = new byte[sizee+1];
fs.Read(rawData, 0, sizee);
fs.Close();
new MySqlCommand(string.Format("INSERT INTO image VALUES(NULL,'{0}',{1})", rawData, sizee), mycon).ExecuteNonQuery();
This code is work fine and insert data successfully.But when i trying to retrieve data it throw an exception No imaging component suitable to complete this operation was found.
Here is the code which is use to retrieve data.
MySqlConnection mycon = new MySqlConnection(string.Format("Server=127.0.0.1;Port=3306;Database=test;Uid=root;Pwd=123456;"));
mycon.Open();
MySqlCommand mycom = new MySqlCommand("Select * from image", mycon);
MySqlDataReader myData = mycom.ExecuteReader();
myData.Read();
int filesize = myData.GetInt32(myData.GetOrdinal("size"));
byte[] mydatya=new byte[filesize];
myData.GetBytes(myData.GetOrdinal("myImage"), 0, mydatya, 0, filesize);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(mydatya);
bitmapImage.EndInit();
It is generally considered better practice to put only references to files in a database and physically save the files in a folder.
I used this code for inserting records in a person table in my DB
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Image img = Image_Box.Image;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
this.personTableAdapter1.Insert(NIC_Box.Text.Trim(), Application_Box.Text.Trim(), Name_Box.Text.Trim(), Father_Name_Box.Text.Trim(), DOB_TimePicker.Value.Date, Address_Box.Text.Trim(), City_Box.Text.Trim(), Country_Box.Text.Trim(), ms.GetBuffer());
but when i retrieve this with this code
byte[] image = (byte[])Person_On_Application.Rows[0][8];
MemoryStream Stream = new MemoryStream();
Stream.Write(image, 0, image.Length);
Bitmap Display_Picture = new Bitmap(Stream);
Image_Box.Image = Display_Picture;
it works perfectly fine but if i update this with my own generated Query like
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Image img = Image_Box.Image;
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
Query = "UPDATE Person SET Person_Image ='"+ms.GetBuffer()+"' WHERE (Person_NIC = '"+NIC_Box.Text.Trim()+"')";
the next time i use the same code for retrieving the image and displaying it as used above . Program throws an exception
alt text http://www.freeimagehosting.net/image.php?3bb5f0d4b3.jpg][img]http://www.freeimagehosting.net/uploads/th.3bb5f0d4b3.jpg
So can any one tell me why i can't figure it out.
Query = "UPDATE Person SET Person_Image =#pic WHERE (Person_NIC = '" + NIC_Box.Text.Trim() + "')";
SqlCommand cmd = new SqlCommand(Query);
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = ms.GetBuffer();
cmd.Parameters.Add(picparameter);
db.ExecuteSQL(Query);
This thing worked with this code hurray lolz