views:

38

answers:

2

I'm trying to load images (pdfs and Word documents) from a memory stream so I can manipulate them before they get added to a pdf. Whenever I try and load a bitmap or a GIF I get one of the dreaded GDI+ errors.

This call...

System.Drawing.Bitmap myImage = System.Drawing.Image.FromStream(docStream);  

Generates this error...

System.Runtime.InteropServices.ExternalException occurred
  Message="A generic error occurred in GDI+."
  Source="System.Drawing"
  ErrorCode=-2147467259
  StackTrace:
       at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData)
       at System.Drawing.Image.FromStream(Stream stream)  

and this call...

System.Drawing.Bitmap myImage = new System.Drawing.Bitmap(docStream);

Generates this error...

System.ArgumentException occurred
  Message="Parameter is not valid."
  Source="System.Drawing"
  StackTrace:
       at System.Drawing.Bitmap..ctor(Stream stream)

The code works for png, jpg and tif, but not for bmp or GIF.

It's basically:

MemoryStream docStream = GetMemoryStream(filePath);
// The next line errors...
System.Drawing.Bitmap myImage = new System.Drawing.Bitmap(docStream);

    private MemoryStream GetMemoryStream(string file)
    {
        FileStream fs = null;
        Byte[] bytes;
        int len;

        fs = File.OpenRead(file);
        len = (int)fs.Length - 1;
        bytes = new Byte[len];
        fs.Read(bytes, 0, len);

        return new MemoryStream(bytes);

    }

I'm not closing the MemoryStream anywhere and unless the png and jpg aren't affected by a closed MemoryStream I don't think that's the issue. When I look at the image files using a hex editor it doesn't appear that the encoding is incorrect. I've also tried different file sizes, just in case.

At this point I'm pretty much at a loss. Any help would be greatly appreciated.

Thanks.

+3  A: 
    len = (int)fs.Length - 1;

Not sure why you thought that was a good idea, used to program in VB? Drop the -1, you want to read all the bytes, not all the bytes minus the last one. File.ReadAllBytes() would be a good choice.

Hans Passant
It was VB code that I ran through a converter. :( Stupid. Thanks.
bill_the_loser
+2  A: 

There is no guarantee that Read fills the buffer; simply itmust return some data. A more common approach might be:

byte[] buffer = new byte[2048];
int read;
while((read = source.Read(buffer, 0, buffer.Length)) > 0) {
    memStream.Write(buffer, 0, read);
}
memStream.Position = 0; //rewind to read it
Marc Gravell