C# 将位图数据提取到字节数组
比方说,我有一个字节数组,其中包含没有标题的原始位图数据。C# 将位图数据提取到字节数组,c#,image,image-processing,bitmap,C#,Image,Image Processing,Bitmap,比方说,我有一个字节数组,其中包含没有标题的原始位图数据。 但是位图数据有点奇怪,我不太确定,但是如果宽度为NPOT(不是二的幂),位图数据似乎没有正确对齐 我使用以下代码从此类位图数据构造bmp: public Bitmap GetBitmap(byte[] bitmapData, int width, int height) { Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format16bppRgb555);
但是位图数据有点奇怪,我不太确定,但是如果宽度为NPOT(不是二的幂),位图数据似乎没有正确对齐 我使用以下代码从此类位图数据构造bmp:
public Bitmap GetBitmap(byte[] bitmapData, int width, int height)
{
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format16bppRgb555);
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
unsafe
{
byte* ptr = (byte*)bmpData.Scan0;
for (int i = 0; i < bitmapData.Length; i++)
{
*ptr = bitmapData[i];
ptr++;
if (width % 2 != 0)
{
if ((i + 1) % (width * 2) == 0 && (i + 1) * 2 % width < width - 1)
{
ptr += 2;
}
}
}
}
bitmap.UnlockBits(bmpData);
return bitmap;
}
公共位图GetBitmap(字节[]位图数据,整数宽度,整数高度)
{
位图位图=新位图(宽度、高度、像素格式.Format16bppRgb555);
矩形rect=新矩形(0,0,bitmap.Width,bitmap.Height);
BitmapData bmpData=位图.LockBits(rect、ImageLockMode.ReadWrite、bitmap.PixelFormat);
不安全的
{
字节*ptr=(字节*)bmpData.Scan0;
对于(int i=0;i
到目前为止,代码运行良好。但由于某些原因,我需要实现“导入位图”,这意味着我需要从位图实例中获取“奇怪”的位图数据
我该怎么做?最后,我想知道怎么做 我决定先通过
封送将数据复制到字节数组中。复制然后将其复制到另一个字节数组中,如果宽度为NPOT,则跳过某一点:
public byte[] ImportBitmap(Bitmap bitmap)
{
int width = bitmap.Width, height = bitmap.Height;
var bmpArea = new Rectangle(0, 0, width, height);
var bmpData = bitmap.LockBits(bmpArea, ImageLockMode.ReadWrite, PixelFormat.Format16bppRgb555);
var data = new byte[bmpData.Stride * Height];
Marshal.Copy(bmpData.Scan0, data, 0, data.Length);
bitmap.UnlockBits(bmpData);
bitmap.Dispose(); // bitmap is no longer required
var destination = new List<byte>();
int leapPoint = width * 2;
for (int i = 0; i < data.Length; i++)
{
if (width % 2 != 0)
{
// Skip at some point
if (i == leapPoint)
{
// Skip 2 bytes since it's 16 bit pixel
i += 1;
leapPoint += (width * 2) + 2;
continue;
}
}
destination.Add(data[i]);
}
return destination.ToArray();
}
public byte[]导入位图(位图)
{
int width=bitmap.width,height=bitmap.height;
var bmpArea=新矩形(0,0,宽度,高度);
var bmpData=bitmap.LockBits(bmpArea,ImageLockMode.ReadWrite,PixelFormat.Format16bppRgb555);
var data=新字节[bmpData.Stride*Height];
Marshal.Copy(bmpData.Scan0,data,0,data.Length);
位图.解锁位(bmpData);
bitmap.Dispose();//不再需要位图
var destination=新列表();
int跳跃点=宽度*2;
for(int i=0;i