日期:2014-05-17  浏览次数:20861 次

Bitmap.Clone问题
程序的功能是点击pictureBox1中的图片,然后在pictureBox2中显示放大后的局部图像。
但是在多次点击后会出现内存不足异常。。
	// 左键单击PictureBoxSource,放大图像
private void pictureBoxSource_MouseClick(object sender, MouseEventArgs e)
{
// 确保已打开图像
if (this.sourceBitmap != null)
{
// 确保为鼠标左键
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
// 创建一个以鼠标点击点为中心,宽度和高度都为50像素的矩形
int x = e.X - 25;
int y = e.Y - 25;
Rectangle clipRect = new Rectangle(x, y, 50, 50);

                    // 不知道这里有没有必要释放先前的图像?
if (this.magnifyBitmap != null)
this.magnifyBitmap.Dispose();
try
{
this.magnifyBitmap = this.sourceBitmap.Clone(
clipRect,
System.Drawing.Imaging.PixelFormat.DontCare);
// 显示放大后的图像
this.pictureBoxPhotoMagnify.Image = this.magnifyBitmap;
}
catch (OutOfMemoryException ex) // 多次点击后会捕获此异常
{
MessageBox.Show(ex.Message);
}

}
}
}

------解决方案--------------------

//从源图像矩形区域绘制到目标区域,目标区域的大小就是缩放的大小
g.DrawImage(srcImage,destRct,srcRct,GraphicsUnit.Pixel);