我的教授有点“挑战我”创建一个应用程序,逐个像素地绘制一个在Bitmap中转换的图像,其中的数据以某种二进制形式保存,我无法将其包裹起来。
以下是给我的例子:
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); //Path is image location
Byte[] bindata = new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
Bitmap bmp;
using (var ms = new MemoryStream(bindata))
{
bmp = new Bitmap(ms);
}
pictureBox1.Image = bmp; //For now, I just display the converted image on screen
现在,如果字节数据类型保存从0到255的数字,这怎么可能?在我给出的示例代码中,还有“Word”数据类型的使用,但在我的IDE中它似乎不存在。
我已经编写了将输入中给出的任何图像转换为位图的代码:
u3556354.wl.sendgrid.net
现在我想下一步是每个字节绘制图像字节,但是我不能理解这个二进制文件和单词数据类型..任何一种帮助都是值得赞赏的:)
答案 0 :(得分:0)
如果你只想一次绘制一个位图像素,你可以这样做:
Bitmap b = new Bitmap(10, 10);
b.SetPixel(0, 0, Color.Black);
b.SetPixel(1, 3, Color.Red);
pictureBox1.Image = b;
答案 1 :(得分:0)
您只需将字节复制到Bitmap的内存缓冲区本身即可。
BitmapData bufferData = buffer.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
bufferData.SetPixel(x, y, CELL_DEAD);
buffer.UnlockBits(bufferData);
//////////
public static unsafe void SetPixel(BitmapData data, int x, int y, byte pixel)
{
*((byte*)data.Scan0 + y * data.Stride + x) = pixel;
}
我已将它用作不安全的,但你可以用IntPtr发挥你的魔力。当然,您必须使用宽度 - 高度同步来发挥自己的作用。
UPD:谨慎设置PixelFormat
。如果您的颜色是默认的256色调色板,或者您想要定义自己的调色板,则需要PixelFormat.Format8bppIndexed
。