解决C#中picturebox加载大图报内存溢出问题

     C#中picturebox对加载的图片分配的内存有一定的限制,当图片宽*高*pdi超过限定后,系统将抛出内存不足且无法显示图片内容。为解决该问题,需要对图片进行处理,将原图片按指定的位置像素填充到目标图片中。代码如下

/// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="sBmp"></param>
        private void ShowPicture(Bitmap sBmp)
        {
            if (sBmp == null)
                return;
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
            }
            //获取图像的BitmapData对像 
            BitmapData sData = sBmp.LockBits(new Rectangle(0, 0, sBmp.Width, sBmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
            Bitmap dBmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            BitmapData dData = dBmp.LockBits(new Rectangle(0, 0, dBmp.Width, dBmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            //循环处理 
            //将项目的“可编译不安全代码”属性设置为true就可以了,方法如下:项目属性对话框——配置属性——生成——允许不安全代码块设置true
            unsafe
            {
                byte* ptrSource = (byte*)(sData.Scan0);
                byte* ptrDes = (byte*)(dData.Scan0);
                int nHeight = dData.Height / 2;
                int nWidth = dData.Width / 2;
                int nOIndexY = 0;
                int nOIndexX = 0;


                for (int y = 0; y < dData.Height; y++)
                {
                    nOIndexY = (int)Math.Round((pOffset.Y + y) / dPictureShowScale, 0, MidpointRounding.AwayFromZero);
                    for (int x = 0; x < dData.Width; x++)
                    {
                        int indexDes = 0;
                        int indexSource = 0;
                        nOIndexX = (int)Math.Round((pOffset.X + x) / dPictureShowScale, 0, MidpointRounding.AwayFromZero);
                        if (0 < nOIndexX && nOIndexX < sData.Width && 0 < nOIndexY && nOIndexY < sData.Height)
                        {
                            indexDes = y * dData.Stride + x * 3;
                            indexSource = nOIndexY * sData.Stride + nOIndexX * 3;
                            ptrDes[indexDes] = ptrSource[indexSource];
                            ptrDes[indexDes + 1] = ptrSource[indexSource + 1];
                            ptrDes[indexDes + 2] = ptrSource[indexSource + 2];
                        }
                    }
                }
                dBmp.UnlockBits(dData);
                sBmp.UnlockBits(sData);
            }
            pictureBox1.Image = dBmp;
        }

pOffset 为原图片偏移量,dPictureShowScale为缩放比例

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值