如何在C#中将文件路径的图像转换为位图

3
Bitmap  bmp = new Bitmap("D:\1.jpg");

我得到的异常是:
参数无效。
我该如何解决?

2
反斜杠:\n 表示换行。要转义它们,请将其加倍,或在字符串文字前面加上 @ 符号。 - Cee McSharpface
2个回答

7

通常情况下这样做是有效的,您是否使用转义字符来转义转义字符?例如:

Bitmap bm = new Bitmap("D:\\newfolder\\1.jpg");
//Notice the \\ the second \ escapes the first

或者像这样转义:

Bitmap bm = new Bitmap(@"D:\newfolder\1.jpg");
//Notice the @ in front of the string, that means ignore the escape characters

您的原始字符串未转义,因此插入了一个换行符(\n)。

0
你需要使用FromFile方法来加载图片。
try
{
    Bitmap image1 = (Bitmap) Image.FromFile(@"C:\Documents and Settings\" +
        @"All Users\Documents\My Music\music.bmp", true);

}
catch(System.IO.FileNotFoundException)
{
    MessageBox.Show("There was an error opening the bitmap." +
        "Please check the path.");
}

使用 Bitmap(String) - 其中字符串是文件路径,有什么问题吗?只是好奇。 - FakeCaleb
构造函数或使用Image.FromFile没有问题。但是,OP忘记转义 \ - Panagiotis Kanavos
@FakeCaleb 没什么。我的回答对于使用情况来说有点过度设计了。EpicKip的回答可能更合适。 - Harrison Perry
@HarrisonPerry 是的,我也是这么想的,只是一个好奇的问题,没有别的意思。 - FakeCaleb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接