image in MySQL database

Dec 26 2009 2:15 PM
I have problem with image into mysql(blob). I'll paste some of my code and if you know what's the problem or have some suggestions please help.

 private byte[] imagedata=null;

//this function is for retrieving data from mysql(blob)

private byte[] getImage()
{
MySqlConnection objConn;
objConn = new MySqlConnection("SERVER=localhost;" +
"DATABASE=database;" +
"UID=root;" +
"PASSWORD=root;charset=utf8");

string strSql = "SELECT * FROM customers where id=" + this.id;
DataSet ds = new DataSet();
MySqlDataAdapter tempAP = new MySqlDataAdapter(strSql, objConn);
MySqlCommandBuilder objCommand = new MySqlCommandBuilder(tempAP);
tempAP.Fill(ds, "customers");

try
{
objConn.Open();
byte[] buffer = (byte[])ds.Tables["customers"].Rows[0][13];
return buffer;
}
catch { objConn.Close(); return null; }
finally { objConn.Close(); }

}

//this function read from file to byte[]

private byte[] ReadFile(string sPath)
{
byte[] data = null;

FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;

FileStream fStream = new FileStream(sPath, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);

data = br.ReadBytes((int)numBytes);
return data;
}

//browse resize upload image (WORKS)
private void button5_Click(object sender, EventArgs e)
{
pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
string imageName = GenerateId();
imageName = imageName + ".jpg";
this.slika = imageName;


OpenFileDialog open = new OpenFileDialog();

open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

if (open.ShowDialog() == DialogResult.OK)
{
System.Reflection.Assembly exe = System.Reflection.Assembly.GetEntryAssembly();
string exePath = System.IO.Path.GetDirectoryName(exe.Location);
string fullImageName = exePath +"\\images\\"+ imageName;
ResizeImage(open.FileName, fullImageName , 240, 240, false);

imagedata = ReadFile(fullImageName);

System.IO.MemoryStream stream1 = new System.IO.MemoryStream(imagedata, true);
stream1.Write(imagedata, 0, imagedata.Length);
Bitmap m_bitmap = (Bitmap)Bitmap.FromStream(stream1);
pictureBox1.Image = m_bitmap;
}
}

Then i insert imagedata into database
 mysql_cmd.CommandText = "insert into customers (image) Values ('" + imagedata + "')";

and this also WORKS...imagedata is in the database (blob field)

But when i try to get image from database

 imagedata = getImage();
if (imagedata != null)
{
System.IO.MemoryStream stream1 = new System.IO.MemoryStream(imagedata, true);
stream1.Write(imagedata, 0, imagedata.Length);
Bitmap m_bitmap = (Bitmap)Bitmap.FromStream(stream1);
pictureBox1.Image = m_bitmap;
}
i have error message