[英]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?如何将 8 位灰度图像的数据放入字节数组? 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.但是由于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.在我的应用程序中,我需要为每个像素一个字节来表示 0-255 的灰度值。
I have solved my problem with ImageSharp我已经用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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.