views:

366

answers:

1

I'm trying to "resave" an image and am getting the error "A generic error occurred in GDI+". I've done some searching around this error, however haven't found a solution yet! Most of the suggestions mention:

  • Checking that the stream isn't in use or locked (i.e. File streams)
  • Make sure the stream isn't disposed for the lifetime of the object (shouldn't be as you'll see below)
  • Attempting to replicate the object within a Bitmap object, and using that to save (didn't work for me)

The code I'm using is listed below:

using (Stream @imageStream = ResourceManager.CreateFile(finalResourceId, imageFileName))
{
    using (MemoryStream ms = new MemoryStream(imageFile.ResourceObject))
    {
        using (Image img = Image.FromStream(ms))
        {
            imageWidth = img.Width;
            imageHeight = img.Height;
            img.Save(@imageStream, img.RawFormat);
        }
     }
 }

In the code above, ResourceManager.CreateFile returns the equivalent of a MemoryStream, therefore there shouldn't be any "resourcing issues".

I don't suppose anyone else has come across this issue and is able to share their solution? Thanks in advance for your help!

+1  A: 

Thanks for @Scozzard for prompting me to think of a workaround!

int imageWidth, imageHeight;
using (Stream imageStream = ResourceManager.CreateFile(finalResourceId, imageFileName))
{
    using (Image img = Image.FromStream(new MemoryStream(imageFile.ResourceObject)))
    {
        imageWidth = img.Width;
        imageHeight = img.Height;
    }
    imageStream.Write(imageFile.ResourceObject, 0, imageFile.ResourceObject.Length);
}

Because I'm working completely in memory I don't really need to use the image object to re-save it as it is in the same image format - I can just copy the byte buffer to the new stream.

Thanks for your comments nevertheless!

Paul Mason
haha no worries - nice work!
Scozzard