c# - 使用内存映射 View 查看大位图图像

标签 c# image bitmap memory-mapped-files

我有一个非常大的位图,我正尝试使用 C# 应用程序查看它。

这里的主要问题是我无法将它直接加载到内存中,因此我尝试使用内存映射 View 库使用来自 Reference One 的指南加载它。 , Reference Two , Reference Three , Reference FourReference Five .

到目前为止我达到的是以下内容:- 根据需要分部分读取位图(例如,我读取了前 200 行)。 从我读取的行创建另一个位图并显示它。

问题:- 重建后的位图图像部分丢失了颜色信息,上下颠倒显示。

示例:- [注意我在这里使用小尺寸图像并尝试显示它的一部分以进行测试]

真实形象:- enter image description here

输出应该是(选择前 200 行并重建一个较小的位图并显示它):- enter image description here 正如您所看到的,重建的图像是无色的并且是上下颠倒的。

现在是代码部分:- 负责整个过程的BMPMMF类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;

namespace BMPViewer
{
    class BMPMMF
    {
        /// <summary>
        /// It opens the image using memory mapped view and read the needed 
        /// parts, then call CreateBM to create a partially bitmap
        /// </summary>
        /// <param name="bmpFilename">Path to the physical bitmap</param>
        /// <returns></returns>
        public Bitmap readPartOfImage(string bmpFilename)
        {
            var headers = ReadHeaders(bmpFilename);
            var mmf = MemoryMappedFile.CreateFromFile(bmpFilename, FileMode.Open);
            int rowSize = headers.Item2.RowSize;    // number of byes in a row

           // Dictionary<ColorObject, int> rowColors = new Dictionary<ColorObject, int>();

            int colorSize = Marshal.SizeOf(typeof(MyColor));
            int width = rowSize / colorSize;//(headers.Item1.DataOffset+ rowSize) / colorSize;
            int height = 200;
            ColorObject cObj;
            MyColor outObj;
            ColorObject[][] rowColors = new ColorObject[height][];
            // Read the view image and save row by row pixel
            for (int j = 0; j < height; j++)
            {
                rowColors[j] = new ColorObject[width];
                using (var view = mmf.CreateViewAccessor(headers.Item1.DataOffset + rowSize * j, rowSize, MemoryMappedFileAccess.Read))
                {
                    for (long i = 0; i < rowSize; i += colorSize)
                    {

                        view.Read(i, out outObj);
                        cObj = new ColorObject(outObj);
                        rowColors[j][i / colorSize] = cObj;


                    }
                }
            }
            return CreateBM( rowColors );

        }
        /// <summary>
        /// Used to create a bitmap from provieded bytes 
        /// </summary>
        /// <param name="rowColors">Contains bytes of bitmap</param>
        /// <returns></returns>
        private Bitmap CreateBM(ColorObject[][] rowColors )
        {
            int width = rowColors[0].Count();
            int height = rowColors.Count();
            //int width = rowColors.Values.Where(o => o == 0).Count();
            Bitmap bitm = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            // new Bitmap(imgdat.GetUpperBound(1) + 1, imgdat.GetUpperBound(0) + 1, PixelFormat.Format24bppRgb);
            BitmapData bitmapdat = bitm.LockBits(new Rectangle(0, 0, bitm.Width, bitm.Height), ImageLockMode.ReadWrite, bitm.PixelFormat);
            int stride = bitmapdat.Stride;
            byte[] bytes = new byte[stride * bitm.Height];

            for (int r = 0; r < bitm.Height; r++)
            {

                for (int c = 0; c < bitm.Width; c++)
                {
                    ColorObject color = rowColors[r][c];
                    bytes[(r * stride) + c * 3] = color.Blue;
                    bytes[(r * stride) + c * 3 + 1] = color.Green;
                    bytes[(r * stride) + c * 3 + 2] = color.Red;

                }
            }


            System.IntPtr scan0 = bitmapdat.Scan0;
            Marshal.Copy(bytes, 0, scan0, stride * bitm.Height);
            bitm.UnlockBits(bitmapdat);

            return bitm;
        }

        /// <summary>
        /// Returns a tuple that contains necessary information about bitmap header 
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private Tuple<BmpHeader, DibHeader> ReadHeaders(string filename)
        {
            var bmpHeader = new BmpHeader();
            var dibHeader = new DibHeader();
            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (var br = new BinaryReader(fs))
                {
                    bmpHeader.MagicNumber = br.ReadInt16();
                    bmpHeader.Filesize = br.ReadInt32();
                    bmpHeader.Reserved1 = br.ReadInt16();
                    bmpHeader.Reserved2 = br.ReadInt16();
                    bmpHeader.DataOffset = br.ReadInt32();

                    dibHeader.HeaderSize = br.ReadInt32();
                    if (dibHeader.HeaderSize != 40)
                    {
                        throw new ApplicationException("Only Windows V3 format supported.");
                    }
                    dibHeader.Width = br.ReadInt32();
                    dibHeader.Height = br.ReadInt32();
                    dibHeader.ColorPlanes = br.ReadInt16();
                    dibHeader.Bpp = br.ReadInt16();
                    dibHeader.CompressionMethod = br.ReadInt32();
                    dibHeader.ImageDataSize = br.ReadInt32();
                    dibHeader.HorizontalResolution = br.ReadInt32();
                    dibHeader.VerticalResolution = br.ReadInt32();
                    dibHeader.NumberOfColors = br.ReadInt32();
                    dibHeader.NumberImportantColors = br.ReadInt32();
                }
            }

            return Tuple.Create(bmpHeader, dibHeader);
        }
    }

    public struct MyColor
    {
        public byte Red;
        public byte Green;
        public byte Blue;
        //public byte Alpha;
    }
    public class ColorObject
    {
        public ColorObject(MyColor c)
        {
            this.Red = c.Red;
            this.Green = c.Green;
            this.Blue = c.Blue;
           // this.Alpha = c.Alpha;
        }
        public byte Red;
        public byte Green;
        public byte Blue;
       // public byte Alpha;
    }

    public class BmpHeader
    {
        public short MagicNumber { get; set; }
        public int Filesize { get; set; }
        public short Reserved1 { get; set; }
        public short Reserved2 { get; set; }
        public int DataOffset { get; set; }
    }

    public class DibHeader
    {
        public int HeaderSize { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public short ColorPlanes { get; set; }
        public short Bpp { get; set; }
        public int CompressionMethod { get; set; }
        public int ImageDataSize { get; set; }
        public int HorizontalResolution { get; set; }
        public int VerticalResolution { get; set; }
        public int NumberOfColors { get; set; }
        public int NumberImportantColors { get; set; }
        public int RowSize
        {
            get
            {
                return 4 * ((Bpp * Width) / 32);
            }
        }
    }
}

这是如何使用它:-

   Bitmap bmpImage = bmp.readPartOfImage(filePath); // path to bitmap
   pictBoxBMP.Image = bmpImage; // set the picture box image to the new Partially created bitmap 

我寻求的解决方案:- 正确显示部分创建的位图,我猜测位图重建或使用内存映射 View 读取位图有问题。

更新#1:申请后 @TaW solution我得到了显示的颜色,即使它们与原始颜色有点不同,但它被接受了。 enter image description here

最佳答案

对于反转部分,您必须检查输入位图数据的顺序(自下而上或自上而下)。 您可以通过检查 DibHeader Height 属性的符号来执行此操作。 通常,负高度表示自上而下的布局。 https://msdn.microsoft.com/en-us/library/windows/desktop/dd183376%28v=vs.85%29.aspx

然后您知道是否必须反转数据,将输入位图的第一行复制到目标位图的最后一行。

        for (int r = 0; r < bitm.Height; r++)
        {

            for (int c = 0; c < bitm.Width; c++)
            {
                ColorObject color = rowColors[r][c];
                bytes[( (bitm.Height - r - 1) * stride) + c * 3] = color.Blue;
                bytes[( (bitm.Height - r - 1) * stride) + c * 3 + 1] = color.Green;
                bytes[( (bitm.Height - r - 1) * stride) + c * 3 + 2] = color.Red;

            }
        }

关于c# - 使用内存映射 View 查看大位图图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28310592/

相关文章:

python - 如果满足条件,如何将像素值设置为特定值?

java - 在屏幕中将耗时显示为 Score java libgdx

c# - 我们可以在 foreach 中使用多个变量吗

c# - c#和asp.net有什么关系?

c# - 过滤后如何将位置应用于节点

Java位图合成如何

android - 无法使用 Picasso 和 scrollGalleryView 从内存中删除位图

c# - 什么是 Humble Object 模式,它何时有用?

image - Matlab 将图像恢复为原始颜色

html - 在不可复制的网页上显示图像