I'm developing a Winforms application. This code contains it to save an image to a SQL Server table. But sometimes a Out of memory exception happens when I'm returning the binary data from the table to display the image.
This is my code to convert image before save.
openImage.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (openImage.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openImage.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
lblImgInfo.Text = openImage.FileName;
FRM_ImageViewer imgver = new FRM_ImageViewer(openImage.FileName);
imgver.Show();
string strFn = openImage.FileName;
FileInfo fiImage = new FileInfo(strFn);
long m_lImageFileLength =fiImage.Length;
byte[] m_barrImg = new byte[Convert.ToInt32(m_lImageFileLength)];
FileStream fs = new FileStream(strFn, FileMode.Open, FileAccess.Read, FileShare.Read);
int iBytesRead = fs.Read(m_barrImg, 0,Convert.ToInt32(m_lImageFileLength));
fs.Close();
}
and this is my code to retrieve the image from the database
// DTSelectedJobs is a DataTable in csharp.
byte[] barrImg = (byte[])DTSelectedJobs.Rows[0].ItemArray[11];
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs2 = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
fs2.Write(barrImg, 0, barrImg.Length);
fs2.Flush();
fs2.Close();
FRM_ImageViewer imgvwr = new FRM_ImageViewer(strfn);
imgvwr.Show();
Can someone please give me an advice how to find the error?
Bitmapinherits fromImagewhich is Disposable, you need to dispose of your bitmap.FileStreamthis code contains it to save an image to sql server table.WHOA, STOP RIGHT THERE. Never save images to a database!!m_barrImg? Also assumingFRM_ImageVieweropens the file, combined with theBitmapcreated forpictureBox1, you'll have three copies of the same image in memory. What exactly are you converting?