2016-05-23 56 views
1

我试着用FileStream读取图像文件,并将它成功地阅读它,但它输出此错误消息如何正确读取图像文件?

“参数无效”。

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; 
    } 
} 
+0

您是否了解[此位图构造函数](https://msdn.microsoft.com/zh-cn/library/0cbhe98f.aspx)?你可以尝试删除'stream.Close()',它将被自动关闭,因为它被封装在'using'中。 – Blorgbeard

+0

指出...我可以知道什么原因“参数无效” –

回答

2

使用

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; 
} 
+1

选项1是理想的(+1),它负责所有内部处理。 –

1

当从流开口,所述流必须保持开放。

我建议您使用将文件路径作为参数的位图构造函数。

return new Bitmap(Fname); 
+0

啊,是的,[这里](https://msdn.microsoft.com/en-us/library/93z9ee4x.aspx)是MSDN的报价:“您必须保持该流在图像的整个生命周期中打开。“ – Blorgbeard