首页 > 解决方案 > 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); 

标签: c#asp.net-mvc

解决方案


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?
}

推荐阅读