4

我正在尝试将位图转换为图标,并且需要设置位图的调色板(请参阅GetHicon from a 16 COLOR bitmap returns an image with less colours)。为此,我试图遵循这个答案:但我看到调色板是空的,我无法创建新数组,因为我必须更改原始数组。(无论如何我什至尝试过。它不起作用。)

我有:

ColorPalette palette = bitmap.Palette;
Color[] entries = palette.Entries;

但是entries的长度为零。

那么如何更改调色板呢?

4

1 回答 1

5

如前所述,位图文件不一定有调色板。事实上,超过 256 种颜色的现代颜色文件不太可能(但仍然可以(我认为))使用调色板。相反,颜色信息来自像素值本身(而不是指向调色板表)

我从( http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/4a10d440-707f-48d7-865b-1d8804faf649/)找到了以下代码。我没有对其进行测试(尽管作者声明“在 VS 2008 c# 中使用 .net 3.5 进行了测试”)。

它似乎可以自动处理减少颜色的数量......

[System.Runtime.InteropServices.DllImport("user32.dll")]
extern static bool DestroyIcon(IntPtr handle);

private void buttonConvert2Ico_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog

    openFileDialog1.InitialDirectory = "C:\\Data\\\" ;
    openFileDialog1.Filter = "BitMap(*.bmp)|*.bmp" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            string sFn = openFileDialog1.FileName;
            MessageBox.Show("Filename=" + sFn);
            string destFileName = sFn.Substring(0, sFn.Length -3) +"ico";

            // Create a Bitmap object from an image file.
            Bitmap bmp = new Bitmap(sFn);
            // Get an Hicon for myBitmap. 
            IntPtr Hicon = bmp.GetHicon();
            // Create a new icon from the handle. 
            Icon newIcon = Icon.FromHandle(Hicon);
            //Write Icon to File Stream
            System.IO.FileStream fs = new System.IO.FileStream(destFileName, System.IO.FileMode.OpenOrCreate);
            newIcon.Save(fs);
            fs.Close();
            DestroyIcon(Hicon);
            setStatus("Created icon From=" + sFn + ", into " + destFileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read/write file. Original error: " + ex.Message);
        }
    }
}
于 2012-12-17T19:53:24.283 回答