1

i store my website image in form of byte array , but when i try to save them as jpeg file ,some of this file throw exception.here is my code for get image:

IList<PropertyInfo> properties = typeof(ApplicationUser).GetProperties()
                               .Where(x => x.PropertyType == typeof(Byte[])).ToList();

var imaBytes = property.GetValue(user, null) as Byte[];
if (imaBytes == null || imaBytes.Length == 0) continue;

Image userImage = ImageHelper.byteArrayToImage(imaBytes);   
userImage.Save(pathname + $@"\{DirName}\" + property.Name + ".jpg", ImageFormat.Jpeg);  

and this is my ImageHelper.byteArrayToImage :

public static Image byteArrayToImage(byte[] byteArrayIn)
{
    try
    {
        using (MemoryStream ms = new MemoryStream(byteArrayIn))
        using (var image = Image.FromStream(ms,false,true))
        {
            byteArrayIn = new byte[0];
            return new Bitmap(image); 
        }
    }
    catch (Exception e)
    {
       Logger.log(e);
    }
}

edit:
i wrap MemoryStream and Image code with using statment and change my code and add ImageToDisk method :

public static void ImageToDisk(byte[] byteArrayIn, string pathToSave)
    {
        try
        {
            using (MemoryStream ms = new MemoryStream(byteArrayIn))
            {
                using (var image = Image.FromStream(ms, false, true))
                {
                    image.Save(pathToSave, ImageFormat.Jpeg);
                    image.Dispose();

                }

            }
        }
        catch (Exception e)
        {
            Logger.log(e);
            throw;
        }

    }  

and main code is this:

 foreach (var property in properties)
                    {
                        try
                        {
                            var imaBytes = property.GetValue(user, null) as Byte[];
                            if (imaBytes == null || imaBytes.Length == 0)
                            {
                                continue;
                            }

                            ImageHelper.ImageToDisk(imaBytes, pathname + $@"\{DirName}\" + property.Name + ".jpg");

                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                        }
                    }  

but now am getting system.runtime.interopservices.externalexception
EDIT 2:
i am completely dizzy!!! its seems some user upload images from IE and IE change MIME type to image/PJPEG
enter image description here
error occurred is some file with this MIME type but also some other image/PJPEG files save correctly without any exception
enter image description here how can i resolve this error??

12
  • From earlier experience, the error checking in the image loading code is somewhat flawed so it may simply be that the image file is corrupt, or using extensions or compression methods that .NET doesn't support. For instance, if you have an image that says it is HUUGE then .NET will actually try to load the image and allocate the memory, instead of kicking back an exception. Commented Sep 11, 2018 at 12:03
  • One thing about your code though, why are you allocating two images, why not simply return Image.FromStream(...); instead of doing that in a using block and constructing a bitmap around it? Commented Sep 11, 2018 at 12:05
  • What format is the image in the byte array in? Commented Sep 11, 2018 at 12:06
  • thank you for comment ,images are JPEG but some image are saved correctly! Commented Sep 11, 2018 at 12:06
  • 1
    @MoshheghFaghdan OOM are almost always caused because Dispose() wasn't called on objects that need disposing, lots of temporary objects (like those created by string operations) or frequent resizing of large arrays. All these create temporary objects that will be garbage collected at some point. In the mean time though they create a lot of memory fragmentation. The runtime may not be able to find a large enough block to allocate the new byte array or that new List Commented Sep 11, 2018 at 12:13

1 Answer 1

3

some of this file throw exception

I'm almost sure the problem is with disposing your images. Make sure all resources are released:

using (Image userImage = ImageHelper.byteArrayToImage(imaBytes))
{
  //do whatever you need
  userImage.Save(pathname + $@"\{DirName}\" + property.Name + ".jpg", ImageFormat.Jpeg);
}

Bitmaps consume a lot of memory. Under the hood Image uses GdipLoadImageFromStream method. To release resources, it should be paired with GdipDisposeImage. That's what happens inside Image.Dispose() method.

Sign up to request clarification or add additional context in comments.

4 Comments

Matter of fact the GDI code does not distinguish and throws OOM exceptions even for things like "not enough handles", so not disposing could indeed be a culprit here.
i don't test code yet , but its seem to work correctly ,but what real image was png format?? is error cause for incorrect image format??
No, image format is not important. Just make sure userImage is disposed correctly.
@PawełDyl i try it but currently it exception thrown 'system.runtime.interopservices.externalexception' in system.drawing.dll

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.