Link to home
Start Free TrialLog in
Avatar of mastiSoft
mastiSoft

asked on

24 or 32 bit image with Color List in WPF

Hi, I trying to create bitmap and use the code I found on internet.
  private void Button_Click(object sender, RoutedEventArgs e)
        {
            var width = 300;
            var height = 300;
            List<System.Windows.Media.Color> colors = new
List<System.Windows.Media.Color>();
            colors.Add(System.Windows.Media.Colors.Red);
            colors.Add(System.Windows.Media.Colors.White);
            colors.Add(System.Windows.Media.Colors.Blue);
            colors.Add(System.Windows.Media.Colors.Green);
            BitmapPalette myPalette = new BitmapPalette(colors);


            var bitmap = new WriteableBitmap(width, height, 96, 96,
PixelFormats.Pbgra32, myPalette);
            var stride = (bitmap.Width * bitmap.Format.BitsPerPixel +
7) / 8;
            var pixels = new ushort[width * height];
            for (var y = 0; y < height; ++y)
                for (var x = 0; x < width; ++x)
                {
                    var v = (0x10000 * 2 * x / width + 0x10000 * 3 * y
/ height);
                    var isMirror = (v / 0x10000) % 2 == 1;
                    v = v % 0xFFFF;
                    if (isMirror)
                        v = 0xFFFF - v;

                    pixels[y * width + x] = (ushort)v;
                }

            bitmap.WritePixels(new Int32Rect(0, 0, width, height),
pixels, stride, 0);

            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            using (var stream = System.IO.File.Create("my.png"))
           encoder.Save(stream);
            imageDisplay.Source = bitmap;

        }
I just changed PixelFormats from Gray16 to Pbgra32 and added the color list. then the code stops to works.
In initial version it was this line: bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 2, 0); in my version
            bitmap.WritePixels(new Int32Rect(0, 0, width, height),
pixels, stride, 0);
If I replace stride with width * 2 (or width * 32) the buffer is not enough . If I use stride then there is conflict between pixels which are declared as ushort.
How can I create 24 or 32 bit image with color list?
ASKER CERTIFIED SOLUTION
Avatar of Misha
Misha
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mastiSoft
mastiSoft

ASKER

Thank you very much Misha. It works now . But I had to change the last line also :bitmap.WritePixels(new Int32Rect(0, 0, width, height),pixels, (int)stride, 0);
Thank you for the quick answer!
glad to help you!