C#实现图片特效 ( 八)
九.马赛克效果
原理: 确定图像的随机位置点和确定马赛克块的大小,然后马赛克块图像覆盖随机点即可.
效果图:
实现代码:
马赛克效果 private void button1_Click(object sender, EventArgs e) { //以马赛克效果显示图像 try { int dw = MyBitmap.Width / 50; int dh = MyBitmap.Height / 50; Graphics g = this.pictureBox1.CreateGraphics(); g.Clear(Color.Gray); Point[] MyPoint = new Point[2500]; for (int x = 0; x < 50; x++) for (int y = 0; y < 50; y++) { MyPoint[x * 50 + y].X = x * dw; MyPoint[x * 50 + y].Y = y * dh; } Bitmap bitmap = new Bitmap(MyBitmap.Width, MyBitmap.Height); for (int i = 0; i < 10000; i++) { System.Random MyRandom = new Random(); int iPos = MyRandom.Next(2500); for (int m = 0; m < dw; m++) for (int n = 0; n < dh; n++) { bitmap.SetPixel(MyPoint[iPos].X + m, MyPoint[iPos].Y + n, MyBitmap.GetPixel(MyPoint[iPos].X + m, MyPoint[iPos].Y + n)); } this.pictureBox1.Refresh(); this.pictureBox1.Image = bitmap; } for (int i = 0; i < 2500; i++) for (int m = 0; m < dw; m++) for (int n = 0; n < dh; n++) { bitmap.SetPixel(MyPoint[i].X + m, MyPoint[i].Y + n, MyBitmap.GetPixel(MyPoint[i].X + m, MyPoint[i].Y + n)); } this.pictureBox1.Refresh(); this.pictureBox1.Image = bitmap; } catch (Exception ex) { MessageBox.Show(ex.Message, "信息提示"); } }
十. 油画效果
原理: 对图像中某一范围内的像素引入随机值.
效果图:
实现代码:
油画效果 private void button1_Click(object sender, EventArgs e) { //以油画效果显示图像 Graphics g = this.panel1.CreateGraphics(); //Bitmap bitmap = this.MyBitmap; //取得图片尺寸 int width = MyBitmap.Width; int height = MyBitmap.Height; RectangleF rect = new RectangleF(0, 0, width, height); Bitmap img = MyBitmap.Clone(rect, System.Drawing.Imaging.PixelFormat.DontCare); //产生随机数序列 Random rnd = new Random(); //取不同的值决定油画效果的不同程度 int iModel = 2; int i = width - iModel; while (i > 1) { int j = height - iModel; while (j > 1) { int iPos = rnd.Next(100000) % iModel; //将该点的RGB值设置成附近iModel点之内的任一点 Color color = img.GetPixel(i + iPos, j + iPos); img.SetPixel(i, j, color); j = j - 1; } i = i - 1; } //重新绘制图像 g.Clear(Color.White); g.DrawImage(img, new Rectangle(0, 0, width, height)); }