简体   繁体   中英

Parameter is not valid error on bitmap constructor

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?

PS
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).

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.

尝试使用接收到图像路径的Bitmap构造函数,如下所示:

var b = new Bitmap(imagePath);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM