Creating a grayscale bitmap image pixel by pixel from a 2D byte array

Viewed 41

I want to create an image from a 8x4 matrix like a 2D-array where each element of the matrix is a byte and corresponds to a single pixel(8-bit gray scale). Below illustrates this:

enter image description here

I tried to plot using several examples but I'm not getting pixel by pixel image.

So far I used:

BitmapSource.Create(col, row, 96d, 96d, PixelFormats.Indexed8, null, matrix_1d, stride);

I tried many examples so I don't want to confuse people with all those since I'm not expert in the topic.

EDIT:

Here what I tried after the comments. But still not getting gray scale for bytes:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace GrayScaleWinFormsBitmapTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var byteArray = new byte[8000];
            for (int i = 0; i < byteArray.Length; i++)
            {
                if (i < 1000)
                {
                    byteArray[i] = 0xC0;
                }
                else
                {
                    byteArray[i] = 0xFF;
                }

            }

            Bitmap bmp = ByteToGrayBitmap(byteArray, 100, 80);

            pictureBox1.Image = bmp;
        }
       
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public static Bitmap ByteToGrayBitmap(byte[] rawBytes, int width, int height)
        {
            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
            BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height),
                                            ImageLockMode.WriteOnly, bitmap.PixelFormat);

            Marshal.Copy(rawBytes, 0, bitmapData.Scan0, rawBytes.Length);
            bitmap.UnlockBits(bitmapData);

            for (int c = 0; c < bitmap.Palette.Entries.Length; c++)
                bitmap.Palette.Entries[c] = Color.FromArgb(c, c, c);

            return bitmap;
        }
    }
}

But bytes still represent colors:

enter image description here

0 Answers
Related