开发者

OutOfMemory exception when loading an image in .Net

开发者 https://www.devze.com 2022-12-27 05:11 出处:网络
Im loading an image from a SQL CE db and then trying to load that into a PictureBox. I am saving the image like this:

Im loading an image from a SQL CE db and then trying to load that into a PictureBox.

I am saving the image like this:

if (ofd.ShowDialog() == DialogResult.OK)
            {
                picArtwork.ImageLocation = ofd.FileName;
                using (System.开发者_如何学JAVAIO.FileStream fs = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open))
                {
                    byte[] imageAsBytes = new byte[fs.Length];
                    fs.Read(imageAsBytes, 0, imageAsBytes.Length);
                    thisItem.Artwork = imageAsBytes;
                    fs.Close();
                }
            }

and then saving to the Db using LINQ To SQL.

I load the image back like so:

using (FileStream fs = new FileStream(@"C:\Temp\img.jpg", FileMode.CreateNew ,FileAccess.Write ))
                {
                    byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());
                    fs.Write(img, 0, img.Length);
                }

but am getting an OutOfMemoryException. I have read that this is a slight red herring and that there is probably something wrong with the filetype, but i cant figure what.

Any ideas?

Thanks picArtwork.Image = System.Drawing.Bitmap.FromFile(@"C:\Temp\img.jpg");


Based on the code you provided it seems like you are treating the image as a string, it might be that data is being lost with the conversion from byte[] to string and string to byte[].

I am not familiar with SQL CE, but if you can you should consider treating the data as a byte[] and not encoding to and from string.

I base my assumption in this line of code

byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());


The GDI has the bad behavior of throwing an OOM exception whenever it is not capable of understanding a certain image format. Use Irfanview to see what kind of image that really is, it is likely GDI can't handle it.


My advice would be to not use a FileStream to load images unless you need access to the raw bytes. Instead, use the static methods provided in Bitmap or Image objects:

Image img = Image.FromFile(@"c:\temp\img.jpg")
Bitmap bmp = Bitmap.FromFile(@"c:\temp\img.jpg")

To save the file use .Save method of the Image or Bitmap object:

img.Save(@"c:\temp\img.jpg")
bmp.Save(@"c:\temp\img.jpg")

Of course we don't know what type ArtWork is. Would you care to share that information with us?

0

精彩评论

暂无评论...
验证码 换一张
取 消