我搜索了有关字节数组的所有问题,但我始终失败。我从来没有编码过C#,这方面我是新手。您能帮我如何从字节数组制作图像文件吗?
这是我的函数,它在名为的数组中存储字节 imageData
public void imageReady( byte[] imageData, int fWidth, int fHeight))
伙计们感谢您的帮助。我认为所有这些答案都行得通。但是我认为我的字节数组包含原始字节。这就是为什么所有这些解决方案都不适用于我的代码的原因。
但是我找到了解决方案。也许此解决方案可以帮助其他遇到像我这样的问题的编码人员。
static byte[] PadLines(byte[] bytes, int rows, int columns) {
int currentStride = columns; // 3
int newStride = columns; // 4
byte[] newBytes = new byte[newStride * rows];
for (int i = 0; i < rows; i++)
Buffer.BlockCopy(bytes, currentStride * i, newBytes, newStride * i, currentStride);
return newBytes;
}
int columns = imageWidth;
int rows = imageHeight;
int stride = columns;
byte[] newbytes = PadLines(imageData, rows, columns);
Bitmap im = new Bitmap(columns, rows, stride,
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(newbytes, 0));
im.Save("C:\\Users\\musa\\Documents\\Hobby\\image21.bmp");
该解决方案适用于8位256 bpp(Format8bppIndexed)。如果图像具有其他格式,则应更改PixelFormat
。
现在颜色有问题。一旦解决了这个问题,我就会为其他用户编辑答案。
* PS =我不确定步幅值,但对于8bit,它应该等于列。
此功能也对我有用。此功能将8位灰度图像复制到32位布局中。
public void SaveBitmap(string fileName, int width, int height, byte[] imageData)
{
byte[] data = new byte[width * height * 4];
int o = 0;
for (int i = 0; i < width * height; i++)
{
byte value = imageData[i];
data[o++] = value;
data[o++] = value;
data[o++] = value;
data[o++] = 0;
}
unsafe
{
fixed (byte* ptr = data)
{
using (Bitmap image = new Bitmap(width, height, width * 4,
PixelFormat.Format32bppRgb, new IntPtr(ptr)))
{
image.Save(Path.ChangeExtension(fileName, ".jpg"));
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句