【问题标题】:C# - convert any filetype to bitmap show in picturebox [closed]C# - 将任何文件类型转换为图片框中的位图显示 [关闭]
【发布时间】:2016-12-24 15:19:47
【问题描述】:

我想要一个 OpenFileDialog 来选择任何文件类型并在位图图像中显示文件位。我的意思是所选文件包含一些 0/1 位,我想以黑白图像显示它们。有什么想法吗?

【问题讨论】:

  • 编写一个函数,将任意字节转换为位图图像,然后加载它。

标签: c# bitmap converters bitstream


【解决方案1】:

如果文件是有效的图像文件,您可以像这样简单地读取图像:

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;

【讨论】:

  • 文件不是有效的图像。他想要任意文件的位域的黑白表示。
  • 好吧,这很令人困惑,因为有效的图像文件也由 0 位和 1 位组成。
  • 我将使用Bitmap.LockBits 与每像素 1 位位图来代替 Graphics 对象。 (会写一个答案,但我今天仅限于我的手机)
  • 是的 LockBits 非常快,但也非常低级。此答案中对此进行了描述:Fast work with Bitmaps in C#.
  • 您也可以使用 SaxxonPike 的 DirectBitmap 类:C# - Faster Alternatives to SetPixel and GetPixel for Bitmaps for Windows Forms App。您可以使用directBitmap.Bits[y * Width + x] = color.ToArgb(); 设置像素
猜你喜欢
  • 2013-11-13
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
相关资源
最近更新 更多