简体   繁体   中英

How can I convert an 8-bit grayscale image into a byte[] array in C#?

How can I put the data of an 8-bit grayscale image into a byte array? I have tried the following code:

private byte[] loadBitmap(string filename, int width, int height)
{
    byte[] data = new byte[width * height];
    BitmapData bmpData = null;
    Bitmap slice = new Bitmap(filename);
    Rectangle rect = new Rectangle(0, 0, slice.Width, slice.Height);
    bmpData = slice.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
    int size = bmpData.Height * bmpData.Stride;
    System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, data, 0, size);
    slice.UnlockBits(bmpData);
    return data;
}

But the result of the data array has some errors because of Format8bppIndexed. Any ideas?

I don't know if this can help you but I'll try.

byte[] buffer = null;
System.Drawing.Image newImg = img.GetThumbnailImage(width, height, null, new System.IntPtr());
using (MemoryStream ms = new MemoryStream()) {
    newImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
buffer = ms.ToArray();

It's just a way of what I have already done.

Hope it helps

In my application I need for each pixel a byte that represents the gray values from 0-255.

I have solved my problem with ImageSharp

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;

private static byte[] GetImageData(byte[] imageData)
{
    using (var image = Image.Load<Rgba32>(imageData))
    {
        var buffer = new byte[image.Width * image.Height];
        var index = 0;

        image.ProcessPixelRows(accessor =>
        {
            for (int y = 0; y < accessor.Height; y++)
            {
                Span<Rgba32> pixelRow = accessor.GetRowSpan(y);
                for (int x = 0; x < pixelRow.Length; x++)
                {
                    ref Rgba32 pixel = ref pixelRow[x];
                    buffer[index] = (byte)((pixel.R + pixel.G + pixel.B) / 3);
                    index++;
                }
            }
        });

        return buffer;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM