如何将字符串转换为ImageFormat类属性?

时间:2017-08-01 22:40:44

标签: c#

目前我有这个:

printscreen.Save(myOutputLocation + myImageName + myImageExtension, ImageFormat.Png);

但是,我想用字符串指定ImageFormat类属性,但我不能让它工作:

string myString = textBox1.Text;
printscreen.Save(myOutputLocation + myImageName + myImageExtension, ImageFormat.myString);

3 个答案:

答案 0 :(得分:2)

我会使用反射编写一个方法 ParseImageFormat ,并将其用作

printscreen.Save(myOutputLocation + myImageName + myImageExtension, 
                 ParseImageFormat(myString));

其中 myString 应该是 MemoryBmp,Bmp,Emf,Wmf,Gif,Jpeg,Png,Tiff,Exif,Icon

之一
public static ImageFormat ParseImageFormat(string str)
{
    return (ImageFormat)typeof(ImageFormat)
            .GetProperty(str, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase)
            .GetValue(null);
}

答案 1 :(得分:1)

您只能使用ImageFormat的{​​{3}}中的任何一个:

Bmp, Emf, Exif, Gif, Guid, Icon, Jpeg, MemoryBmp, Png, Tiff, Wmf

如果您想设置自己的格式,请使用

printscreen.Save(myOutputLocation + myImageName + myImageExtension);

答案 2 :(得分:0)

ImageFormat是一个非常简单的类,它只是一些属性和类似属性的方法,所以你不能做你想做的事情。 (无论如何,这都是错的,我稍后会谈到它。)

您可以在此处获取课程内容的详细列表:https://msdn.microsoft.com/en-us/library/system.drawing.imaging.imageformat(v=vs.110).aspx

但是,根据您实际尝试的操作,可能还有其他方法可以执行此操作。我猜你试图根据用户输入以特定格式保存。 ImageFormat.mystring永远不会工作,但如果字符串是支持的格式之一(参见上面的链接),你可能会迭代不同的格式来找到搜索格式。

一个非常基本且相当缓慢的方法就是这样。 (我有一段时间没做过c#,这可能是丑陋的代码。)

ImageFormat[] supported_formats = [ImageFormat.GIF, ImageFormat.Bmp]; /* etc */
byte index = 0;
ImageFormat curr_format;
do 
{
     curr_format = supported_formats[i++];
} while (curr_format.ToString() != user_string);

/* curr_format now holds user-entered format */

现在,至于为什么你的尝试是错误的。

除非你做一些更复杂的东西,使用反射或装饰(也许),你不能以这种方式处理类。您试图强制某个类(ImageFormat)具有一个属性(your_string),该名称将根据动态输入而改变。虽然有可能这样做(正如现在可能在其他答案中提到的那样),但我认为这对于这样一个简单的用例并不合适,并且你可能最终会花费大量时间来处理某些事情(保存)看起来非常需要表演,似乎也经常使用。

然而,您可以找到关于此类事情的文档,因为您可能仍会对各种网站感兴趣。

谷歌给了我那些: http://www.dofactory.com/net/decorator-design-pattern - 装饰者 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection - 反思

相关问题