如何正确读取图像文件?

How to correctly read an image file?

我尝试使用FileStream读取图像文件并成功读取它,但它输出此错误消息

"Parameter is not valid".

public Bitmap streamimage(string Fname)
{
    Bitmap bm;
    using (FileStream stream = new FileStream(Fname, FileMode.Open, FileAccess.Read))
    {
        bm = (Bitmap)Image.FromStream(stream);
        stream.Close();
        return bm;
    }
}

从流中打开时,流必须保持打开状态。

我建议你使用以文件路径为参数的位图构造器。

return new Bitmap(Fname);

使用

Image I = Image.FromFile("FilePath");

并使用该图像

Bitmap bm= new Bitmap(I);

或者

Bitmap bm= new Bitmap("FilePath");

您可以像这样编辑代码

public Bitmap streamimage(string Fname)
{
    Bitmap bm;
    FileStream stream = new FileStream(Fname, FileMode.Open, FileAccess.Read);
    bm = (Bitmap)Image.FromStream(stream);
    return bm;
}