如何将组成文件的原始位显示为位图图像?

时间:2019-04-26 08:18:42

标签: c# file bmp

我想将文件(例如MIDI文件)显示为位图,方法是将文件转换为字节数组,然后从字节中构建位图。

1 个答案:

答案 0 :(得分:1)

一个人可以做以下事情:

        public void Convert()
        {
            string filePath = "C:\\Users\\User\\Desktop\\sample.mid";
            byte[] bytes = File.ReadAllBytes(filePath);
            int pixelCount = (int)Math.Ceiling(bytes.Count() / 4.0);
            double width = Math.Ceiling(Math.Sqrt(pixelCount));
            double height = Math.Ceiling(pixelCount / width);
            string outputPath = "C:\\Users\\User\\Desktop\\sample.bmp";
            SaveAsBmp((int)width, (int)height, bytes, outputPath);
        }

        public void SaveAsBmp(int width, int height, byte[] argbData, string path)
        {
            using (Bitmap img = new Bitmap(width, height, PixelFormat.Format32bppPArgb))
            {
                BitmapData data = img.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, img.PixelFormat);
                for (int y = 0; y < height; y++)
                {
                    Marshal.Copy(argbData, width * y, data.Scan0 + data.Stride * y, width * 4);
                }
                img.UnlockBits(data);
                img.Save(path, ImageFormat.Bmp);
            }
        }

以下内容是从此处提供的示例MIDI中获得的:https://en.wikipedia.org/wiki/File:MIDI_sample.mid?qsrc=3044

enter image description here