我正在用 C# 创建一个 WinForm 应用程序,我可以用它来“嗅出”文件中的一些 24 位位图。我已经收集了信息,例如它的偏移量、关于它在文件中的写入方式的一些分析以及它的长度。
关于文件的更多信息是:
- BMP数据写反了。 (例如:(255 0 0)写成(0 0 255)
- 它没有 BMP header 。只有 BMP 图像数据 block 。
- 像素格式为 24 位。
- 它的 BMP 是纯品红色。 (RGB 中为 255 0 255)
我正在使用以下代码:
using (FileStream fs = new FileStream(@"E:\MyFile.exe", FileMode.Open))
{
int width = 190;
int height = 219;
int StartOffset = 333333; // Just a sample offset
Bitmap tmp_bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Rectangle rect = new Rectangle(0, 0, tmp_bitmap.Width, tmp_bitmap.Height);
System.Drawing.Imaging.BitmapData bmpData =
tmp_bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
tmp_bitmap.PixelFormat);
unsafe
{
// Get address of first pixel on bitmap.
byte* ptr = (byte*)bmpData.Scan0;
int bytes = width * height * 3; //124830 [Total Length from 190x219 24 Bit Bitmap]
int b; // Individual Byte
for (int i = 0; i < bytes; i++)
{
fs.Position = StartOffset - i; // Change the fs' Position [Subtract since I'm reading in reverse]
b = fs.ReadByte(); // Reads one byte from its position
*ptr = Convert.ToByte(b); // Record byte
ptr ++;
}
// Unlock the bits.
tmp_bitmap.UnlockBits(bmpData);
}
pictureBox1.Image = tmp_bitmap;
}
我得到了这个输出。我认为原因是每当它到达下一行时,字节就会变得困惑。 (255 0 255 变为 0 255 255 并继续直到变为 255 255 0)
我希望你能帮我解决这个问题。非常感谢您。
解决方案 现在通过添加此代码(在我 friend 的帮助和 James Holderness 提供的信息的帮助下)修复了此问题
if (width % 4 != 0)
if ((i + 1) % (width * 3) == 0 && (i + 1) * 3 % width < width - 1)
ptr += 2;
非常感谢!
最佳答案
对于标准 BMP,每条单独的扫描线都需要是 4 字节的倍数,因此当您有 24 位图像(每个像素 3 字节)时,您通常需要允许在每条扫描线的末尾进行填充使其达到 4 的倍数。
例如,如果您的宽度为 150 像素,则为 450 字节,需要四舍五入为 452 以使其成为 4 的倍数。
我怀疑这可能是您在这里遇到的问题。
关于C# - 从字节创建 BMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510476/