我有一个项目将图像格式文件转换为图标文件.但是,在转换图像后,图像的颜色会发生变化.
这是我的代码
Bitmap theBitmap = new Bitmap(theImage, new Size(width, height));
IntPtr Hicon = theBitmap.GetHicon();// Get an Hicon for myBitmap.
Icon newIcon = Icon.FromHandle(Hicon);// Create a new icon from the handle.
FileStream fs = new FileStream(@"c:\Icon\" + filename + ".ico", FileMode.OpenOrCreate);//Write Icon to File Stream
Run Code Online (Sandbox Code Playgroud)

谁知道怎么解决这个问题?
Han*_*ant 12
Bitmap.GetHicon()非常擅长创建可在任何可运行.NET代码的Windows版本上运行良好的图标.包括旧版本,Windows 98和Windows 2000.尚未支持花哨图标的操作系统.
所以你得到的是一个只有 16种颜色的图标,使用带有基本颜色的预制调色板.温和地说,这往往会产生令人失望的结果.
Bitmap或Icon类没有获得更好结果的选项.通常,您需要使用图标编辑器来创建好的图标.其中应包含不同大小和颜色深度的多个图像,以便它们适用于任何视频适配器设置和任何操作系统版本.特别是从1600万色到256色或16色的色彩还原是一种非平凡的操作,有多种方法可以做到,它们都不是完美的.一个好的图标编辑器有你需要的工具,使它能够很好地工作.
小智 10
这是我的方法,可以将png转换为图标,包括透明度:
public void ConvertToIco(Image img, string file, int size)
{
Icon icon;
using (var msImg = new MemoryStream())
using (var msIco = new MemoryStream())
{
img.Save(msImg, ImageFormat.Png);
using (var bw = new BinaryWriter(msIco))
{
bw.Write((short)0); //0-1 reserved
bw.Write((short)1); //2-3 image type, 1 = icon, 2 = cursor
bw.Write((short)1); //4-5 number of images
bw.Write((byte)size); //6 image width
bw.Write((byte)size); //7 image height
bw.Write((byte)0); //8 number of colors
bw.Write((byte)0); //9 reserved
bw.Write((short)0); //10-11 color planes
bw.Write((short)32); //12-13 bits per pixel
bw.Write((int)msImg.Length); //14-17 size of image data
bw.Write(22); //18-21 offset of image data
bw.Write(msImg.ToArray()); // write image data
bw.Flush();
bw.Seek(0, SeekOrigin.Begin);
icon = new Icon(msIco);
}
}
using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
icon.Save(fs);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要32位图标,则可以使用FreeImage http://freeimage.sourceforge.net
string icoFile = "C:\path\to\file.ico";
FreeImageBitmap fiBitmap = new FreeImageBitmap(theBitmap);
fiBitmap.Rescale(48, 48, FREE_IMAGE_FILTER.FILTER_BICUBIC);
fiBitmap.Save(icoFile);
fiBitmap.Rescale(32, 32, FREE_IMAGE_FILTER.FILTER_BICUBIC);
fiBitmap.SaveAdd(icoFile);
fiBitmap.Rescale(16, 16, FREE_IMAGE_FILTER.FILTER_BICUBIC);
fiBitmap.SaveAdd(icoFile);
Run Code Online (Sandbox Code Playgroud)
如果要完全支持32,8,4和1位图标,则必须创建自己的ico格式编写器.我在开发自己的基于C#的png到ico转换器http://iconverticons.com时遇到了这个问题
实际上并不太难; 您需要的ico文件格式规范如下:http: //msdn.microsoft.com/en-us/library/ms997538.aspx
你还需要这里的Bitmap头规范,因为ico是位图的一个子集:http: //msdn.microsoft.com/en-us/library/dd183376.aspx
你可以试试这个:
Bitmap theBitmap = new Bitmap(theImage, new Size(width, height));
theBitmap.Save(@"C:\Icon\" + filename + ".ico", System.Drawing.Imaging.ImageFormat.Icon);
Run Code Online (Sandbox Code Playgroud)