c# - How to Convert User input to Encoder value type
问题描述
I have MVC 5 project that use System.Drawing; System.Drawing.Imaging; I want the user to select image quality when it is jpeg This is my approach:
Encoder quality = Encoder.Quality; //quality should be user input
var ratio = new EncoderParameter(quality, 100L);
var codecParams = new EncoderParameters(1);
codecParams.Param[0] = ratio;
convertedImage.Save(outputImagePath, GetEncoder(ImageFormat.Jpeg), codecParams);
Due to some use cases I have public async Task bool and I can't declare encoder parameter. Thus my question: How to convert string(user input) to encoder. If we want to convert string to Int, simple:
var name = Convert.ToInt32(userinput);
解决方案
If you are going to get values like "quality" vs. "colordepth", you could do something like this, as long as you know the possible values:
switch (userInput.ToLower())
{
case "quality":
quality = Encoder.Quality;
break;
case "colordepth":
quality = Encoder.ColorDepth;
break;
// etc....
}
Taking a quick look, it look like the Encoder constructor requires a guid. So, if you wanted to create the encoder from a guid value, the following tries to parse the userInput and create an Encoder if it is a valid guid. It seems like you may actually need to make sure the guid is a valid value for the constructor as well.
Encoder quality;
if (Guid.TryParse(userInput, out Guid result))
{
quality = new Encoder(result);
}
else
{
// default to something if userInput isn't valid?
}
推荐阅读
- node.js - (thread_id_key != 0x7777),函数 find_thread_id_key,文件 ../src/coroutine.cc,第 134 行
- svg - 在 depthTest 和 depthWrite 设置为 true 的情况下加载 SVG 图像会使其自身发生 z-fight
- wordpress - 无法摆脱“woocommerce-product-gallery__trigger”(缩放/全屏按钮)
- ruby-on-rails - 未定义的方法 `api_path' 用于#
- python - Python地板除法运算符打破循环
- sql-server - 特定事件之间的 SQL 滞后
- ravendb - RavenDb:文档刷新功能不会在@refresh 标志指定的时间或之后运行
- apache-kafka - CDC 与 docker 中的 debezium
- asp.net-core - 映射配置文件类中的 Automapper 映射子属性
- javascript - 如何处理来自另一个js而不是service-worker的推送通知?