Create Indexed Color Image in C#


/ Published in: C#
Save to your folder(s)

This snippet shows how to create indexed color bitmap in C#. The code also shows how to access and modify pixel data using LockBits.


Copy this code and paste it in your HTML
  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.Runtime.InteropServices;
  5.  
  6. namespace IndexedImage
  7. {
  8. class IdxImage
  9. {
  10. int[] _red;
  11. int[] _green;
  12. int[] _blue;
  13. public IdxImage()
  14. {
  15. fire();
  16. }
  17.  
  18. public Image GetImage()
  19. {
  20. //allocate new bitmap
  21. //width: paletteSize, height: 16
  22. Bitmap img = new Bitmap(paletteSize(), 16, PixelFormat.Format8bppIndexed);
  23. ColorPalette pal = img.Palette;
  24.  
  25. //fill image palette with color information
  26. fillPalette(ref pal);
  27.  
  28. //setup images
  29. img.Palette = pal;
  30. BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height),
  31. ImageLockMode.ReadWrite, img.PixelFormat);
  32.  
  33. byte[] rowPixels = new byte[img.Width];
  34. for (int k = rowPixels.Length - 1; k >= 0; k--)
  35. rowPixels[k] = (byte)k;
  36.  
  37. IntPtr scan0 = data.Scan0;
  38. for (int h = 0; h < data.Height; h++)
  39. {
  40. Marshal.Copy(rowPixels, 0, scan0, rowPixels.Length);
  41. scan0 = new IntPtr(scan0.ToInt64() + data.Stride);
  42. }
  43.  
  44. img.UnlockBits(data);
  45.  
  46. return img;
  47. }
  48.  
  49. private void fillPalette(ref ColorPalette pal)
  50. {
  51. int N = Math.Min(Math.Min(_red.Length, _green.Length), _blue.Length);
  52. for (int k = 0; k < N; k++)
  53. pal.Entries[k] = Color.FromArgb(_red[k], _green[k], _blue[k]);
  54. }
  55. private int paletteSize()
  56. {
  57. if (_red == null)
  58. return 0;
  59. return Math.Min(Math.Min(_red.Length, _green.Length), _blue.Length);
  60. }
  61.  
  62. /// <summary>
  63. /// Example palette: Fire
  64. /// </summary>
  65. private void fire()
  66. {
  67. _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 };
  68. _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 };
  69. _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 };
  70. }
  71. }
  72. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.