【发布时间】:2016-12-24 15:19:47
【问题描述】:
我想要一个 OpenFileDialog 来选择任何文件类型并在位图图像中显示文件位。我的意思是所选文件包含一些 0/1 位,我想以黑白图像显示它们。有什么想法吗?
【问题讨论】:
-
编写一个函数,将任意字节转换为位图图像,然后加载它。
标签: c# bitmap converters bitstream
我想要一个 OpenFileDialog 来选择任何文件类型并在位图图像中显示文件位。我的意思是所选文件包含一些 0/1 位,我想以黑白图像显示它们。有什么想法吗?
【问题讨论】:
标签: c# bitmap converters bitstream
如果文件是有效的图像文件,您可以像这样简单地读取图像:
Image image = Image.FromFile(pathOfImage);
...然后将其分配给图片框。
您需要引用System.Drawing.dll,并在代码顶部包含using using System.Drawing;。
但是,如果文件中的位代表黑白像素,则需要自己绘制图像。
首先创建一个Bitmap,然后从中创建一个图形对象。然后就可以在上面画像素了。
using (var image = new Bitmap(width, height))
using (var g = Graphics.FromImage(image)) {
// TODO: Draw using the graphics object. (Insert code below)
}
您可以使用此答案中的答案来读取位:BinaryReader - Reading a Single “ BIT ”?
然后,您可以在双循环中遍历这些位。假设位是逐行存储的:
using (var stream = new FileStream("file.dat", FileMode.Open)) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
bool? bit = stream.ReadBit(true);
if (bit == null) { // No more bits
return;
}
if (bit.Value) {
g.FillRectangle(Brushes.White, x, y, 1, 1);
}
}
}
}
最后将图片分配给图片框
pictureBox1.Image = image;
【讨论】:
Bitmap.LockBits 与每像素 1 位位图来代替 Graphics 对象。 (会写一个答案,但我今天仅限于我的手机)
DirectBitmap 类:C# - Faster Alternatives to SetPixel and GetPixel for Bitmaps for Windows Forms App。您可以使用directBitmap.Bits[y * Width + x] = color.ToArgb(); 设置像素