using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace Ex13_32 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Bitmap MyBitmap; private void button2_Click(object sender, EventArgs e) { //打开图像文件 OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "图像文件(JPeg, Gif, Bmp, etc.)|*.jpg;*.jpeg;*.gif;*.bmp;*.tif; *.tiff; *.png| JPeg 图像文件(*.jpg;*.jpeg)|*.jpg;*.jpeg |GIF 图像文件(*.gif)|*.gif |BMP图像文件(*.bmp)|*.bmp|Tiff图像文件(*.tif;*.tiff)|*.tif;*.tiff|Png图像文件(*.png)| *.png |所有文件(*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) { //得到原始大小的图像 Bitmap SourceBitmap = new Bitmap(openFileDialog.FileName); //得到缩放后的图像 MyBitmap = new Bitmap(SourceBitmap, this.pictureBox1.Width, this.pictureBox1.Height); this.pictureBox1.Image = MyBitmap; } } private void button1_Click(object sender, EventArgs e) { //以积木效果显示图像 try { Graphics myGraphics = this.panel1.CreateGraphics (); //Bitmap myBitmap = new Bitmap(this.BackgroundImage); int myWidth, myHeight, i, j, iAvg, iPixel; Color myColor, myNewColor; RectangleF myRect; myWidth = MyBitmap.Width; myHeight = MyBitmap.Height; myRect = new RectangleF(0, 0, myWidth, myHeight); Bitmap bitmap = MyBitmap.Clone(myRect, System.Drawing.Imaging.PixelFormat.DontCare); i = 0; while (i < myWidth - 1) { j = 0; while (j < myHeight - 1) { myColor = bitmap.GetPixel(i, j); iAvg = (myColor.R + myColor.G + myColor.B) / 3; iPixel = 0; if (iAvg >= 128) iPixel = 255; else iPixel = 0; myNewColor = Color.FromArgb(255, iPixel, iPixel, iPixel); bitmap.SetPixel(i, j, myNewColor); j = j + 1; } i = i + 1; } myGraphics.Clear(Color.WhiteSmoke); myGraphics.DrawImage(bitmap, new Rectangle(0, 0, myWidth, myHeight)); } catch (Exception ex) { MessageBox.Show(ex.Message, "信息提示"); } } } }