Saving and retrieving image in SQL database from C# problem - c#

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

Related

Unable to render image from Oracle BLOB, data from BLOB is consistently 28 bytes larger

I am trying to save an image to an oracle table within a BLOB field, later use it to display the image on a web page. For some reason when i retrieve the image data its consistently exactly 28 bytes larger than the original.
I load the image from the file using:
return Image.FromFile(HttpContext.Current.Server.MapPath(filename));
Save the image in a memory stream, then convert to array:
var ms = new MemoryStream();
imageIn.Save(ms, imageIn.RawFormat);
return ms.ToArray();
Insert the data into the table: (Note I have tried both ODBC and Oracle)
var Isql = $"INSERT INTO PAS_IMAGE_TEST (PROD_DATE, IMAGE_DATA) VALUES
(TO_DATE('...','...'), :IMAGE_DATA)";
var cmdI = new OracleCommand(Isql, cn);
var pI = cmdI.Parameters.Add("IMAGE_DATA", OracleDbType.Blob);
pI.Direction = System.Data.ParameterDirection.Input;
pI.Value = byteArrayIn;
cmdI.ExecuteNonQuery();
This seems to work, the row is there.
I select the data:
var Isql = $"SELECT IMAGE_DATA FROM PAS_IMAGE_TEST WHERE PROD_DATE = TO_DATE('{ProdDate.ToString(common_database.CS_DATEFORMAT)}','{common_database.OR_DATEFORMAT}')";
var cmd = new OracleCommand(Isql, cn);
return cmd.ExecuteScalar(); - returns first rows/first column afaik.
Convert the object to a bytearray:
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
Convert it to a B64 url:
return $"data:image/{fileType};charset=utf-8;base64," + Convert.ToBase64String(imageArray);
Supplying this string to an html src should display the image. It doesn't... fact is that if I used to original byte array (data from step 2) prior to saving it works expected.

WPF - Retrieve (Select OR Download) Image from Mysql Database in WPF using C#

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

Get varbinary image into C# DataSet with SqlDataReader

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

Parameter is not valid Exception while displaying image from database

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

Save and retrieve images from mysql database

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.

Categories

Resources