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为缩放比例