C# 将图像深度限制为特定设置

C# 将图像深度限制为特定设置,c#,.net,image-processing,colors,C#,.net,Image Processing,Colors,我想把一个图像转换成一个特定的预设集。尽管做了几次尝试,我仍然在最终图像中得到了我提供的调色板中没有的颜色。我正在使用下面的代码并用我的颜色填充可用的颜色 private static Image GetImageInPalette(string imagePath, List<System.Windows.Media.Color> availableColors) { BitmapImage bmpSource = new BitmapImage(new Uri(

我想把一个图像转换成一个特定的预设集。尽管做了几次尝试,我仍然在最终图像中得到了我提供的调色板中没有的颜色。我正在使用下面的代码并用我的颜色填充可用的颜色

private static Image GetImageInPalette(string imagePath, List<System.Windows.Media.Color> availableColors) {

        BitmapImage bmpSource = new BitmapImage(new Uri(imagePath));
        BitmapPalette colorPalette = new BitmapPalette(availableColors);
        FormatConvertedBitmap bmpWithPalette = new FormatConvertedBitmap(bmpSource, PixelFormats.Indexed8, colorPalette, 0);

        var encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmpWithPalette));
        Image destinationImage;
        using (var ms = new MemoryStream()) {
            encoder.Save(ms);
            destinationImage = Image.FromStream(ms);
        }
        return destinationImage;
    }
私有静态图像GetImageInPalette(字符串imagePath,列表可用颜色){
BitmapImage bmpSource=新的BitmapImage(新Uri(imagePath));
BitmapPalette colorPalette=新的BitmapPalette(可用颜色);
FormatConvertedBitmap bmpWithPalette=新的FormatConvertedBitmap(bmpSource,PixelFormats.Indexed8,colorPalette,0);
var encoder=新的BmpBitmapEncoder();
Add(BitmapFrame.Create(bmpWithPalette));
图像目的图像;
使用(var ms=new MemoryStream()){
编码器保存(ms);
destinationImage=Image.FromStream(毫秒);
}
返回目标图像;
}

图像似乎仍在使用最近邻的某种变体。

是否指定了所有256种可能的颜色?“不”,我猜是可以推断出来的。谢谢汉斯。所以,如果我不提供256种独特的颜色,其余的将被“填充”?我想拍摄一张图像,并将其缩小到31种预定义颜色的最大调色板。这可能吗?一个简单的方法是用索引0颜色的副本填充调色板的剩余条目。或者编写自己的最近颜色匹配算法,使用数组而不是调色板。