功能及需求:pictureBox里图像的缩放,要求不保存缩放后的图像,只对原图像进行查看式缩放,且图像缩小然后放大,处理图像失真的问题。
注意事项:一、图像不保存。二、图像缩小后放大的失真要处理。
难点:图像缩小后放大的失真
解决方法:保存原始图像Initial,图像放大时比较pictureBox1.Image.width和Initial.width的大小,
如果。pictureBox1.Image.width小于Initial.width
把放大看成缩小来计算
代码说明:
#region |图像缩放|
/// <summary>
/// 图像放大
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Large_Click(object sender, System.EventArgs e)
{
if(pic.Width>panPic.Width&pic.Height>panPic.Height&pic.Image.Height>=Initial.Height*4)
{
MessageBox.Show("图像已最大");
}
else
{
Rectangle oldrct;
Bitmap bmp;
bmp = (Bitmap)this.pic.Image;
oldrct = new Rectangle(0, 0, bmp.Width, bmp.Height);
this.pic.Image = bmp;
Bitmap tmpbmp = null;
tmpbmp = new Bitmap(bmp.Width*2, bmp.Height*2);
if(bmp.Width<Initial.Width)
{
oldrct = new Rectangle(0, 0, Initial.Width, Initial.Height);
Graphics g = Graphics.FromImage(tmpbmp);
Rectangle newrct = new Rectangle(0,0, tmpbmp.Width, tmpbmp.Height);
g.DrawImage(Initial, newrct, oldrct, GraphicsUnit.Pixel);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pic.Image = tmpbmp;
g.Dispose();
pic.Update();
}
else
{
Graphics g = Graphics.FromImage(tmpbmp);
Rectangle newrct = new Rectangle(0,0, tmpbmp.Width, tmpbmp.Height);
g.DrawImage(bmp, newrct, oldrct, GraphicsUnit.Pixel);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pic.Image = tmpbmp;
g.Dispose();
pic.Update();
}
}
}
/// <summary>
/// 图像缩小
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Narrow_Click(object sender, System.EventArgs e)
{
if(this.pic.Image.Width<this.panPic.Width&this.pic.Height<this.panPic.Height)
{
MessageBox.Show("图像已缩到最小");
}
else
{
Rectangle oldrct;
Bitmap bmp;
bmp = (Bitmap)this.pic.Image;
oldrct = new Rectangle(0, 0, bmp.Width, bmp.Height);
this.pic.Image = bmp;
Bitmap tmpbmp = null;
tmpbmp = new Bitmap(bmp.Width / 2, bmp.Height / 2);
Graphics g = Graphics.FromImage(tmpbmp);
Rectangle newrct = new Rectangle(0,0, tmpbmp.Width, tmpbmp.Height);
g.DrawImage(bmp, newrct, oldrct, GraphicsUnit.Pixel);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pic.Image = tmpbmp;
g.Dispose();
pic.Update();
}
}
#endregion