Saving Image into SQL Server database - c#

When I insert an image into a SQL Server database, if the image is null, then it inserts a 0x value into the database image column.
When I retrieve the image with 0x hex value, I get an error:
Parameter is not valid
string strsql = "SELECT [ID],PIC_Name FROM [HRMS].[dbo].[Employee_PC] where Id = '" + mFieldValue1 + "'";
myconn = new OleDbConnection(clsConnections.conString);
myconn.Open();
cmd = new OleDbCommand(strsql, myconn);
OleDbDataReader dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((byte[])dr[1] == null )
//if (picData == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream ms = new MemoryStream((byte[])dr[1]);
ms.Position = 0;
pictureBox1.Image = new Bitmap(ms);
}
}

dr[1] won't be null, so neither will (byte[])dr[1]. You want to check the first byte in that array.
byte[] picData = (byte[])dr[1];
if (picData[0] == 0)
{
pictureBox1.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(picData);
ms.Position = 0;
pictureBox1.Image = new Bitmap(ms);
}

Related

How can I update binary data in database

I want to make update query which will update all data in textbox, combobox and picture box. When I created query for Textbox and combobox, it's working fine. but when I add picturebox image binary data, somehow query stopped working and it's also not showing any error, it just not updating data. I want to update all data in database
Here the code
private void updatebill()
{
if (cn.State == ConnectionState.Closed)
{
cn.Open();
}
da = new OleDbDataAdapter();
dt = new DataTable();
ds = new DataSet();
string str;
str = "UPDATE BillTable set [Bill_No]= '"+ billno.Text + "', [Bill_Year] = '" + fylabel.Text + "', [Group_ID]= '" + groupidDB + "', [Vendor_Id]= '" + vendoridDB + "', [Amount]= '" + amount.Text + "', Picture1= #pict1 , Picture2= #pict2, Picture3= #pict3, Picture4= #pict4 where (ID= #billID)";
cmd = new OleDbCommand(str, cn);
cmd.Parameters.AddWithValue("#billID", Convert.ToString(BillIdentity.Text));
cmd.Parameters.AddWithValue("#voucher", Convert.ToString(voucher.Text));
// picture box
if (PictureBox1.Image != null)
{
Bitmap bitmap = new Bitmap(PictureBox1.Image);
byte[] pic = ImageToBytes(bitmap, System.Drawing.Imaging.ImageFormat.Jpeg);
cmd.Parameters.AddWithValue("#pict1", pic);
}
else
{
cmd.Parameters.AddWithValue("#pict1", OleDbType.Binary).Value = DBNull.Value;
}
if (pictureBox2.Image != null)
{
Bitmap bitmap = new Bitmap(pictureBox2.Image);
byte[] pic2 = ImageToBytes(bitmap, System.Drawing.Imaging.ImageFormat.Jpeg);
cmd.Parameters.AddWithValue("#pict2", pic2);
}
else
{
cmd.Parameters.AddWithValue("#pict2", OleDbType.Binary).Value = DBNull.Value;
}
if (pictureBox3.Image != null)
{
Bitmap bitmap = new Bitmap(pictureBox3.Image);
byte[] pic3 = ImageToBytes(bitmap, System.Drawing.Imaging.ImageFormat.Jpeg);
cmd.Parameters.AddWithValue("#pict3", pic3);
}
else
{
cmd.Parameters.AddWithValue("#pict3", OleDbType.Binary).Value = DBNull.Value;
}
if (pictureBox4.Image != null)
{
Bitmap bitmap = new Bitmap(pictureBox4.Image);
byte[] pic4 = ImageToBytes(bitmap, System.Drawing.Imaging.ImageFormat.Jpeg);
cmd.Parameters.AddWithValue("#pict4", pic4);
}
else
{
cmd.Parameters.AddWithValue("#pict4", OleDbType.Binary).Value = DBNull.Value;
}
cmd.ExecuteNonQuery();
cn.Close();
}
private byte[] ImageToBytes(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (System.IO.MemoryStream menStream = new System.IO.MemoryStream())
{
image.Save(menStream, format);
return menStream.ToArray();
}
}

Deserialize binary array from database C#

I am trying to save and retrieve a file to and from a database. I am serializing the object ans saving it as binary. However, when trying to deserialize I get the error that the input stream is not a valid binary format. I tried several solutions and this is what I've put together so far:
public void saveFile(string filename, string file, object o)
{
byte[] myFile;
if (o != null)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, o);
myFile= ms.ToArray();
}
String insert = "INSERT INTO user_files(FileName, Username, File) VALUES ('myfile','noname','"+ myFile + "')";
MySqlCommand command = new MySqlCommand(insert, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
MessageBox.Show("Sorry, something went wrong");
}
finally
{ connection.Close(); }
}
And here is the Load
public TrafficMonitor LoadFile(string user, string filename)
{
TrafficMonitor obj = null;
byte[] myFile = null;
DataTable dt = new DataTable();
MySqlDataAdapter getCommand = new MySqlDataAdapter("Select File from user_files where Username='noname' and filename='myfile'" , connection);
try
{
connection.Open();
getCommand.Fill(dt);
foreach (DataRow row in dt.Rows)
{
myFile= (byte[])row["File"];
}
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(myFile, 0, myFile.Length);
memStream.Seek(0, SeekOrigin.Begin);
obj = (TrafficMonitor)binForm.Deserialize(memStream);
}
catch { MessageBox.Show("Sorry, something went wrong"); }
finally { connection.Close(); }
return obj;
}
Here is how I inserted binary data to MySQL:
byte[] imgBuffer = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
MySqlCommand query = new MySqlCommand();
query.Connection = _connection;
query.CommandText = "INSERT INTO Photos(id,img) VALUES(?id,?img)";
var id = Guid.NewGuid();
query.Parameters.Add("?id", MySqlDbType.Binary).Value = id.ToByteArray();
query.Parameters.Add("?img", MySqlDbType.Blob).Value = imgBuffer;
query.ExecuteNonQuery();
And how I read binary data from MySQL:
MySqlCommand query = new MySqlCommand();
query.Connection = _connection;
query.CommandText = "SELECT * FROM Photos WHERE id=#ID";
query.Parameters.Add("#id", MySqlDbType.Binary).Value = guid.ToByteArray();
using (MySqlDataReader reader = query.ExecuteReader())
{
if (reader.Read())
{
Guid id = reader.GetGuid(0);
byte[] imgBuffer = (byte[])reader.GetValue(1);
}
}

retrieve blob picture from mysql database c#

I use this code to retrieve my picture and it work corectly with a simple table that contain only blob but when i'm trying to adapt it for my table user that containt (cin,nom,prenom....,image) exception that indicate
"Paramétre non valid" (not a valid parameter)
int bufferSize = 1000;
try
{
string SQL = "Select image from user ";
MySqlCommand cmd = new MySqlCommand(SQL, db.Connection);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "image");
int c = ds.Tables["image"].Rows.Count;
db.CloseConnection();
if (c > 0)
{
Byte[] byteBLOBData = new Byte[bufferSize];
byteBLOBData = (Byte[])(ds.Tables["image"].Rows[c - 1]["image"]);
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(stmBLOBData);
MessageBox.Show("bien chargée");
}
}
catch (Exception ex)
{
MessageBox.Show("Connection Error!\n" + ex.Message, "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Try this one...
DataTable userTable;
DataTable ds;
int cin;
string nom;
string prenom;
Byte[] ImageByte;
userTable = ds;
if (userTable == null)
return false;
else
{
if (userTable.Rows.Count > 0)
{
foreach (DataRow userRow in userTable.Rows)
{
cin = Convert.ToInt32(userRow["cin"]);
nom = userRow["nom"].ToString();
prenom = userRow["prenom"].ToString();
ImageByte = (Byte[])(userRow["image"]);
}
}
}
if (ImageByte != null)
{
// You need to convert it in bitmap to display the imgage
pictureBox1.Image = ByteToImage(ImageByte);
pictureBox1.Refresh();
}
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
byteBLOBData = ((Byte[])ds.Tables["image"].Rows[c - 1]["image"]);
This should solve it.

how to retrieve image from database into picturebox in c#

private void view_Load(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SOFT;Initial Catalog=Dev01;Integrated Security=True";
con.Open();
//Retrieve BLOB from database into DataSet.
SqlDataReader myReader = null;
SqlCommand cmd = new SqlCommand("select * from empdetails", con);
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
lbl_fname.Text = myReader["firstname"].ToString();
lbl_mname.Text = myReader["middlename"].ToString();
lbl_lname.Text = myReader["lastname"].ToString();
lbl_gender.Text = myReader["gender"].ToString();
lbl_dob.Text = myReader["dob"].ToString();
lbl_qualification.Text = myReader["qualification"].ToString();
lbl_skills.Text = myReader["skills"].ToString();
lbl_userid.Text = myReader["username"].ToString();
lbl_pwd.Text = myReader["password"].ToString();
lbl_cpwd.Text = myReader["confirmpassword"].ToString();
lbl_mno.Text = myReader["mobilenumber"].ToString();
lbl_altmno.Text = myReader["alternativenumber"].ToString();
lbl_email.Text = myReader["email"].ToString();
lbl_presentadd.Text = myReader["presentaddress"].ToString();
lbl_permanentadd.Text = myReader["permanentaddress"].ToString();
}
myReader.Close();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "empdetails");
int c = ds.Tables["empdetails"].Rows.Count;
if (c > 0)
{
//BLOB is read into Byte array, then used to construct MemoryStream,
//then passed to PictureBox.
//SqlCommand cmd1=new SqlCommand("Select photo from empdetails");
Byte[] bytedata = new Byte[0];
bytedata = (Byte[])(ds.Tables["empdetails"].Rows[c - 1]["photo"]);
MemoryStream ms = new MemoryStream(bytedata);
pictureBox1.Image = Image.FromStream(ms,true); //HERE I AM GETTING ERROR
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I already checked various pages but that didn't solve my problem. I am getting an error only in this part:
"pictureBox1.Image = Image.FromStream(ms,true);"
The data type of your column should be image try
public byte[] ConvertImageToByte(Image image, ImageFormat format)
{
var stream = new MemoryStream();
image.Save(stream, format);
return stream.ToArray();
}
public Image ConvertBytesToImage(object _image)
{
byte[] byteImage = (byte[])(_image);
MemoryStream ms = new MemoryStream(byteImage);
ms.Write(byteImage, 0, byteImage.Length);
Image img = Image.FromStream(ms);
return img;
}
Saving the byte in your database
OpenFileDialog file = new OpenFileDialog();
file.Title = "Please Select the Employee Photo (Dimension 128x128)";
file.Filter = "JPEG Files|*.jpg|Bitmap Files|*.bmp|Gif Files|*.gif|PNG Files|*.png";
file.DefaultExt = "jpg";
file.ShowDialog();
if (!string.IsNullOrEmpty(file.FileName))
{
byte[] bytePhoto = ConvertImageToBytes(Image.FromFile(file.FileName), ImageFormat.Png);
//bytePhoto is the object to save in your database
}
Retrieve the byte and display as image
byte[] bytePhoto = (byte[])ds.Tables["empdetails"].Rows[0]["Photo"];
pictureBox1.Image = ConvertBytesToImage(bytePhoto);

How to display images with fixed dimensions in ASP.NET after retrieving them from a MySQL database

Following are the links which describe connection to MySQL:
http://www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx
http://www.codeproject.com/KB/aspnet/image_asp.aspx
Here is the code to display image from mysql database:
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
// string commantext = "select img_id,img_file,img_type,img_name from image";
// DataSet ds = MySqlHelper.ExecuteDataset(conn, commantext);
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
// DataTable dt = ds.Tables[0];
DataTable dt = GetData(cmd);
while(dt !=null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
// Byte[] bytes = (Byte[])dt.Rows[1][] ;
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["img_type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["img_name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
conn.Close();
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
My code to upload image file to mysql database is as below.
protected void Button1_Click(object sender, EventArgs e)
{
Stream img_strm = File1.PostedFile.InputStream;
int img_len = File1.PostedFile.ContentLength;
string strtype = File1.PostedFile.ContentType;
//code snippet to determine image height and width.
System.Drawing.Image i = System.Drawing.Image.FromStream(img_strm);
int fileheight = int.Parse(i.Width.ToString());
int filewidth = int.Parse(i.Height.ToString());
strname = Text1.Value;
//Session["t"] = strname;
byte[] imgData = new byte[img_len];
int n = img_strm.Read(imgData, 0, img_len);
int result = saveToDb(strname, imgData, strtype);
}
private int saveToDb(string imgName, byte[] imgbin, string imgContenttype)
{
string db = "server=localhost;database=test;uid=root;password=techsoft";
MySqlConnection conn = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand("insert into image(img_name,img_file,img_type) values(?img_name,?img_file,?img_type)", conn);
//MySqlParameter param0 = new MySqlParameter("?img_id", MySqlDbType.Int16, 20);
//param0.Value = ;
//cmd.Parameters.Add(param0);
MySqlParameter param0 = new MySqlParameter("?img_name", MySqlDbType.VarChar, 45);
param0.Value = imgName;
cmd.Parameters.Add(param0);
// MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.VarChar, 45);
MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.LongBlob, 10);
param1.Value = imgbin;
cmd.Parameters.Add(param1);
MySqlParameter param2 = new MySqlParameter("?img_type", MySqlDbType.VarChar, 45);
param2.Value = imgContenttype;
cmd.Parameters.Add(param2);
conn.Open();
int num = cmd.ExecuteNonQuery();
conn.Close();
return num;
}
I have used binary writer to display. Can anybody suggest how to display images in fixed dimensions?
I would resize the images on the page being used to display them. Where are they being displayed?
or
I would resize the images at the time they are saved
Assuming your only challenge is to only scale the images(either before uploading or when retrieving them)...here is some code i use to get scaled dimensions for an image (to fit specific fixed dimensions)...you can stick this somewhere in an imaging class
Note that there are many approaches...
public static Size getScaledDimensions( Image img, Int32 maxW, Int32 maxH)
{
//check if image is already within desired dimensions
if (img.Height <= maxH & img.Width <= maxW)
{
Size orgsize = new Size(img.Width, img.Height);
return orgsize; // no need to rescale
}
else //proceed with rescaling
{
int finalH;
int finalW;
//use height/width ratio to determine our new dimensions
double hwRatio = (double)img.Height / (double)img.Width;
int newW = (int) (maxH/ hwRatio);
int newH = (int) (hwRatio * maxW);
//make sure we scale the right dimension
if (newW <= maxW) // scale width
{
finalH = maxH;
finalW = newW;
}
else
{ // scale height
finalH = newH;
finalW = maxW;
}//end if
Size newsize = new Size(finalW, finalH);
return newsize;
}
Thanks for all the support from rip and The_AlienCoder for their answers. I have found out answer to my own query.
We need to use streams to convert binary data from mysql database. Later graphic library should be used to load the streams. In the meantime we need to resize the image according to our need.
protected void Page_Load(object sender, EventArgs e){
//Create connection to mysql database.
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
//create datatable. GetData is a method to fetch the data.
DataTable dt = GetData(cmd);
//Get data from database to bytes.
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
//Defining the size to display data.
int outputSize = 100;
if (bytes.Length > 0)
{
// Open a stream for the image and write the bytes into it
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, true);
stream.Write(bytes, 0, bytes.Length);
Bitmap bmp = new Bitmap(stream);
Size new_size = new Size();
//resize based on the longer dimension
if (bmp.Width > bmp.Height)
{
new_size.Width = outputSize;
new_size.Height = (int)(((double)outputSize / (double)bmp.Width) * (double)bmp.Height);
}
else
{
new_size.Width = (int)(((double)outputSize / (double)bmp.Height) * (double)bmp.Width);
new_size.Height = outputSize;
}
Bitmap bitmap = new Bitmap(new_size.Width, new_size.Height, bmp.PixelFormat);
Graphics new_g = Graphics.FromImage(bitmap);
new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
new_g.DrawImage(bmp, -1, -1, bitmap.Width + 1, bitmap.Height + 1);
bmp.Dispose();
bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
new_g.Dispose();
stream.Close();
}
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager .ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
}

Categories