Return to Snippet

Revision: 55906
at February 28, 2012 13:03 by putu


Initial Code
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
            Bitmap img = new Bitmap(paletteSize(), 16, PixelFormat.Format8bppIndexed);
            ColorPalette pal = img.Palette;

            //fill image palette with color information
            fillPalette(ref pal);

            //setup images
            img.Palette = pal;
            BitmapData data = img.LockBits(new Rectangle(0, 0, img.Width, img.Height),
                ImageLockMode.ReadWrite, img.PixelFormat);

            byte[] rowPixels = new byte[img.Width];
            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);
                scan0 = new IntPtr(scan0.ToInt64() + data.Stride);
            }

            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 };
        }
    }
}

Initial URL

                                

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

Initial Title
Create Indexed Color Image in C#

Initial Tags
image

Initial Language
C#