'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?
Solution 1:[1]
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
Solution 2:[2]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | profanis |
| Solution 2 | live2 |
