如何在c#中将png-24转换为png-8

如何在c#中将png-24转换为png-8

问题描述:

如何在C#中将PNG-24转换为PNG-8



基本上我想减少c#win表单应用程序中的图像大小。



我尝试下面的代码但不适用于PNG,所以我需要不同的方法。



什么我试过了:



How to convert PNG-24 to PNG-8 in C#

Basically i want to reduce a size of image in c# win forms application.

I tried below code but not working in the case of PNG so i need different method.

What I have tried:

private void VaryQualityLevel()
{
    // Get a bitmap.
    Bitmap bmp1 = new Bitmap(@"c:\TestPhoto.jpg");
    ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
 
    // Create an Encoder object based on the GUID
    // for the Quality parameter category.
    System.Drawing.Imaging.Encoder myEncoder =
        System.Drawing.Imaging.Encoder.Quality;
 
    // Create an EncoderParameters object.
    // An EncoderParameters object has an array of EncoderParameter
    // objects. In this case, there is only one
    // EncoderParameter object in the array.
    EncoderParameters myEncoderParameters = new EncoderParameters(1);
 
    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
    myEncoderParameters.Param[0] = myEncoderParameter;
    bmp1.Save(@"c:\TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters);
}
 
private ImageCodecInfo GetEncoder(ImageFormat format)
{
 
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
 
    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

搜索.net位图缩小颜色深度时,Google的第一个结果是位图的快速颜色深度变化 [ ^ ]。它提供了函数 ConvertTo8bppFormat 这应该是你想要的。
When searching for ".net bitmap reduce color depth" the first result with Google is Fast Color Depth Change for Bitmaps[^]. It provides the function ConvertTo8bppFormat which should be what you want.