0

I know, I know... there are many others posts like this. I didn't find what I was look for, let's move on.

I break a PDF into images using this GhostScript implementation for C# and then try to load each image into a Bitmap, sometimes it gives me a Parameter is not valid error on this line:

[...]new Bitmap((Image)Image.FromFile(imagePath))[...]


Image.FromFile(imagePath) successfully returns an Image (though I think it's returning a Bitmap) but then Bitmap's constructor gives me the error. What am I doing wrong?

P.S.
I'm casting the result to Image because when I quick watch the result of Image.FromFile(...) it shows it as a System.Drawing.Bitmap (either way, cast, no cast, yields the same result).

PedroC88
  • 3,708
  • 7
  • 43
  • 77
  • 1
    Are you sure Image.FromFile is actually loading something? What version of .net are you using. Have you tried to just do `new Bitmap(imagePath)`? There's a constructor in Bitmap that takes a path – Jaime Apr 13 '12 at 21:08
  • I used the Bitmap constructor as you suggested and it seems to be working fine. I'm fixing some other minor bugs and then I'll test again. – PedroC88 Apr 13 '12 at 21:20
  • Write an answer, that was it. – PedroC88 Apr 13 '12 at 21:35

2 Answers2

3

You shouldn't create a new bitmap from the bitmap, just cast the reference to the bitmap that you have already:

Bitmap b = (Bitmap)Image.FromFile(imagePath);

If you create a new bitmap from the bitmap that you load from the file, you don't get any reference to the bitmap that you loaded. As you can't dispose that bitmap you will leave them for the garbage collector to finalise, and if that doesn't happen fast enough you may run out of memory.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2

Try using the Bitmap constructor that receives a path to the image like so:

var b = new Bitmap(imagePath);
Jaime
  • 6,736
  • 1
  • 26
  • 42