Thursday, September 14, 2017

OutOfMemoryException: Out of memory Saving Bitmap

OutOfMemoryException: Out of memory Saving Bitmap

If out of memory exception occurs catch the exception and write the code which is in catch block





     DataTable DT //result from DB
     MemoryStream ms;
     Bitmap bp;
            for (int i = 0; i < DT.Rows.Count; i++)
            {
                String filename = DT.Rows[i]["ID"].ToString() + ".jpg";
                string RootFolder = @"E:\FTPData\ERPWebForTest\StudentPictures";
                string path = Path.Combine(RootFolder, filename);
                try
                {
                    ms = new MemoryStream((byte[])DT.Rows[i]["DisplayImage"]);
                    bp = new Bitmap(ms);
                    bp.Save(path);
                }
                catch (Exception) //in case of out of memory exception
                {
                    ms = new MemoryStream((byte[])DT.Rows[i]["DisplayImage"]);
                    byte[] buffer = new byte[4096];
                    int byteSeq = ms.Read(buffer, 0, 4096);
                    ms.Write(buffer, 0, byteSeq);

                }

            }