Bitmap.Save to save an icon actually saves a .png

后端 未结 3 1862

I need to write a program that will generate 108 combinaisons of icons (standard windows .ico files) based on a tileset image.

I use the class System.Drawing.Bitmap

3条回答
  •  囚心锁ツ
    2021-01-14 06:01

    I made a quick-and-dirty workaround myself, I post it here for the record (it might help someone that need a quick solution, like me).

    I won't accept this as the correct answer, it's not an actual icon writer. It just write a 32bits ARGB bitmap into an ico file, using PNG format (works on Vista or later)

    It is based on the ICO file format article from Wikipedia, and some fails and retry.

    void SaveAsIcon(Bitmap SourceBitmap, string FilePath)
    {
        FileStream FS = new FileStream(FilePath, FileMode.Create);
        // ICO header
        FS.WriteByte(0); FS.WriteByte(0);
        FS.WriteByte(1); FS.WriteByte(0);
        FS.WriteByte(1); FS.WriteByte(0);
    
        // Image size
        FS.WriteByte((byte)SourceBitmap.Width);
        FS.WriteByte((byte)SourceBitmap.Height);
        // Palette
        FS.WriteByte(0);
        // Reserved
        FS.WriteByte(0);
        // Number of color planes
        FS.WriteByte(0); FS.WriteByte(0);
        // Bits per pixel
        FS.WriteByte(32); FS.WriteByte(0);
    
        // Data size, will be written after the data
        FS.WriteByte(0);
        FS.WriteByte(0);
        FS.WriteByte(0);
        FS.WriteByte(0);
    
        // Offset to image data, fixed at 22
        FS.WriteByte(22);
        FS.WriteByte(0);
        FS.WriteByte(0);
        FS.WriteByte(0);
    
        // Writing actual data
        SourceBitmap.Save(FS, ImageFormat.Png);
    
        // Getting data length (file length minus header)
        long Len = FS.Length - 22;
    
        // Write it in the correct place
        FS.Seek(14, SeekOrigin.Begin);
        FS.WriteByte((byte)Len);
        FS.WriteByte((byte)(Len >> 8));
    
        FS.Close();
    }
    

提交回复
热议问题