一: 打开图像并进行显示与缩放
1.OpenFileDialog类
<span style="font-family:Courier New;"> private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = "D:\\360安全浏览器下载"; openFileDialog.Filter = "images files (*.jpg)|*.jpg|All files(*.*)|*.*"; //表示默认默认为图像文件 openFileDialog.FilterIndex = 1; //指示对话框在关闭前是否还原当前目录 openFileDialog.RestoreDirectory = true; if(openFileDialog.ShowDialog() == DialogResult.OK) { Bitmap bitmap = new Bitmap(openFileDialog.FileName); /*方法一 * */ this.pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize; this.pictureBox1.Image = bitmap;</span>
由此可以看出,OpenFileDialog和PictureBox控件结合使用,从而使外部图像在该控件中显示。当然也可以直接在PictureBox控件的Image属性导入外部图像,这没什么好说的~
2.除了用PictureBox显示图像外,也可以用DrawImage
<span style="font-family:Courier New;"> /*DrawImage的方法有: * (Image image, Rectangle rect) * (Image image, int x, int y)指定显示图片的左上角位置 * (Image image,Ractangle destRect, Rectangle srcRect, GraphicsUnit srcUint) * destRect和srcRect分别表示所绘制图像和源图像的位置和大小,而scrUint为枚举类型的度量单位 * */ Graphics myGraphics = this.CreateGraphics(); myGraphics.DrawImage(bitmap, 100, 100); //设置压缩矩形 Rectangle compressionRectangle = new Rectangle(100, 200, bitmap.Width / 2, bitmap.Height / 2); myGraphics.DrawImage(bitmap, compressionRectangle);</span>
可以使用Graphics的DrawImage方法进行Bitmap实例的一系列操作,Graphic的实例化较为特殊,再看一遍:Graphic myGra = this.CreatGraphics();
二:图像的旋转、反射、扭曲操作
其实依旧是DrawImage的使用,这些操作都是使用:public void DrawImage(Image image, Point[] destPoints),其实这三种操作都是根据Point数组的不同而形成的。Point数组是三个点,定义一个平行四边形。分别表示左上角、右上角、左下角。
<span style="font-family:宋体;"> </span><span style="font-family:Courier New;"> Graphics myGraphics = this.CreateGraphics(); Image image = new Bitmap(bitmap); myGraphics.DrawImage(image, 0, 0); Point[] destinationPoints = { new Point(200,20), //左上角 new Point(110,100), //右上角 new Point(250,30) //左下角 }; myGraphics.DrawImage(image, destinationPoints);</span>
三:复制图像与图像的保存
<span style="font-family:Courier New;font-size:14px;color:#cc33cc;">Graphics myGraphics = this.CreateGraphics(); Bitmap originalBitmap = new Bitmap("pic1.png"); Rectangle sourceRectangle = new Rectangle(0, 0, originalBitmap.Width, originalBitmap.Height / 2); Bitmap secondBitmap = originalBitmap.Clone(sourceRectangle, PixelFormat.DontCare); myGraphics.DrawImage(originalBitmap, 10, 10); myGraphics.DrawImage(secondBitmap, 150, 10); try { if (originalBitmap != null) { originalBitmap.Save("d:\\myBitmap.jpg"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); }</span>