Graphics有个变换矩阵的属性:
Graphics.Transform
相应的方法有:
Graphics.RenderingOrigin// 变换中心属性
Graphics.ResetTransform();// 重置变换矩阵
Graphics.TranslateTransform();// 平移变换
Graphics.RotateTransform();// 旋转变换
Graphics.ScaleTransform();// 缩放变换
Image img = new Bitmap(@"d:/My Documents/My Pictures/H2.jpg");
gp.DrawImage(img, new Rectangle(0, 0, 500, 100));
//new Rectangle(0, 0, 500, 100)为会之后的大小,之后可以更其他参数,例如原始图片大小 想绘制什么大小都行。
你要不失真的话,就用我给你的解决方案。
以下是主要代码:
private void ComputeImageScale(int srcWidth,int srcHeight,ref int destWidth,ref int destHeight)
{
if(destWidth == 0 || destHeight == 0)
return;
try
{
double scale = 0;
if(srcWidth/destWidth > (scale = 1.0*srcHeight/destHeight))
{
scale = 1.0*srcWidth/destWidth;
destHeight = (int)(srcHeight/scale);
}
else
destWidth = (int)(srcWidth/scale);
}
catch{}
}
private void TestImgZoom()
{
string filePath = "C://";
switch(this.cmbType.Text)
{
case "BMP":
filePath += "test.bmp";
break;
case "JPG":
filePath += "test.jpg";
break;
case "GIF":
filePath += "test.gif";
break;
}
try
{
Image img = Image.FromFile(filePath);
int destWidth = 0;
int destHeight = 0;
if(this.radioLength.Checked)
{
destWidth = Convert.ToInt32(this.txtWidth.Text);
destHeight = Convert.ToInt32(this.txtHeight.Text);
}
else
{
destWidth = img.Width/Convert.ToInt32(this.numericUpDownWidth.Value);
destHeight = img.Height /Convert.ToInt32(this.numericUpDownHeight.Value);
}
System.Drawing.Imaging.ImageFormat format = img.RawFormat;
ComputeImageScale(img.Width,img.Height,ref destWidth,ref destHeight);
Bitmap bmp = new Bitmap(destWidth,destHeight,img.PixelFormat);
//Image bmp = null;
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.DrawImage(img,new Rectangle(0,0,destWidth,destHeight),0,0,img.Width,img.Height,GraphicsUnit.Pixel);
this.pictureBox1.Image = bmp;
System.Drawing.ImageConverter imgConvert = new ImageConverter();
//System.IO.FileStream stream = new System.IO.FileStream("C:/test1.gif");
//System.Drawing.Imaging
//bmp.SaveAdd(bmp,
//bmp = (Bitmap)img.GetThumbnailImage(destWidth,destHeight,null,IntPtr.Zero);
//bmp.Save("C://1.gif",format);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}