Question Retrieving Image Error

mahen

New member
Joined
Feb 11, 2018
Messages
4
Programming Experience
5-10
When I try to load picture from sql server database to picture Box in C#. I am getting this error System.outofmemoryException.: Out of Memory at system.drawing.Image.fromfile. I tried a lot to figure out this issue but could not.

So, Please help me out. I am also attaching a snapshot along with this. Snapshot.png


Thanks
 
If you're loading the image from a database then there's no good reason for you to be calling Image.FromFile. Check this out and if you have issues then post your actual code so we can see what you're actually doing so that we can work out what's wrong with that specifically.
 
if (!Dt1.Tables[0].Rows[0][2].ToString().Equals(""))
{
m_barrImg3 = ((byte[])Dt1.Tables[0].Rows[0][2]);


string strfn1 = Convert.ToString(DateTime.Now.ToFileTime());
fs = new FileStream(strfn1, FileMode.CreateNew, FileAccess.Write);
fs.Write(m_barrImg3, 0, m_barrImg3.Length);
fs.Flush();
fs.Close();
fs.Dispose();
pbDoc1.Image.Dispose();
pbDoc1.Image = Image.FromFile(strfn1);---on this line it throws the exception
 
You don't need to save the data to a file to get an Image. Use a MemoryStream.

http://www.vbforums.com/showthread.php?544942-Saving-Images-in-Databases

In short:
var row = Dt1.Tables[0].Rows[0];

if (!row.IsNull(2))
{
    // This will not throw an exception if there's no Image but is only supported in recent versions.
    pbDoc1.Image?.Dispose();

    using (var ms = New MemoryStream((byte[]) row[2]))
    {
        pbDoc.Image = Image.FromStream(ms);
    }
}
 
You don't need to save the data to a file to get an Image. Use a MemoryStream.

http://www.vbforums.com/showthread.php?544942-Saving-Images-in-Databases

In short:
var row = Dt1.Tables[0].Rows[0];

if (!row.IsNull(2))
{
    // This will not throw an exception if there's no Image but is only supported in recent versions.
    pbDoc1.Image?.Dispose();

    using (var ms = New MemoryStream((byte[]) row[2]))
    {
        pbDoc.Image = Image.FromStream(ms);
    }
}
But Earlier I am fetching 3 images as well and they are loading exactly without any exxeption..?so why its happening with these images
 
when I use this code
using (var ms = New MemoryStream((byte[]) row[2]))
{
pbDoc.Image = Image.FromStream(ms);
}
its says arguementexception: parameter is not valid..
 
The fact that the code you had produced the desired results does not mean that it is good code. Don't write the data to a file unless you want a file. If what you want is an Image then a file is pointless.

If the code you had was working in some cases but not this one (maybe that's something that you could have mentioned) and the code that I provided doesn't work either then the data you are getting from the database almost certainly does not represent a valid image. You've saved bad data so you'll never be able to turn it into a valid Image object.
 
Back
Top Bottom