/ Published in: C#
This snippet shows how to create indexed color bitmap in C#. The code also shows how to access and modify pixel data using LockBits.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace IndexedImage { class IdxImage { int[] _red; int[] _green; int[] _blue; public IdxImage() { fire(); } public Image GetImage() { //allocate new bitmap //width: paletteSize, height: 16 ColorPalette pal = img.Palette; //fill image palette with color information fillPalette(ref pal); //setup images img.Palette = pal; ImageLockMode.ReadWrite, img.PixelFormat); for (int k = rowPixels.Length - 1; k >= 0; k--) rowPixels[k] = (byte)k; IntPtr scan0 = data.Scan0; for (int h = 0; h < data.Height; h++) { Marshal.Copy(rowPixels, 0, scan0, rowPixels.Length); } img.UnlockBits(data); return img; } private void fillPalette(ref ColorPalette pal) { int N = Math.Min(Math.Min(_red.Length, _green.Length), _blue.Length); for (int k = 0; k < N; k++) pal.Entries[k] = Color.FromArgb(_red[k], _green[k], _blue[k]); } private int paletteSize() { if (_red == null) return 0; return Math.Min(Math.Min(_red.Length, _green.Length), _blue.Length); } /// <summary> /// Example palette: Fire /// </summary> private void fire() { _red = new int[]{ 0, 0, 1, 25, 49, 73, 98, 122, 146, 162, 173, 184, 195, 207, 217, 229, 240, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; _green = new int[]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 35, 57, 79, 101, 117, 133, 147, 161, 175, 190, 205, 219, 234, 248, 255, 255, 255, 255 }; _blue = new int[] { 0, 61, 96, 130, 165, 192, 220, 227, 210, 181, 151, 122, 93, 64, 35, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 35, 98, 160, 223, 255 }; } } }