毕业工作5年后,你决定利用所掌握的技术,自主创业。你决定开发一款图片特效处理的软件,该软件完成如下功能:
-
该软件包含一个主窗体,该主窗体的标题为“图片特效”。
-
该窗体包括4个PictureBox,4个按钮:4个按钮分别完成利用OpenfileDialog载入一张原始图片,并实现底片效果,灰度效果,以及模糊效果。对应效果如下图所示:
-
底片效果公式:255 - R, 255 – G, 255-B;
-
灰度效果公式:R * 0.299 + G * 0.587 + B * 0.114;
-
模糊效果原理: 求取原图像上x,y相邻的9个像素的颜色平均值,当作新的x,y像素的值。—均值滤波
g = (f(x-1,y-1) + f(x,y-1)+ f(x+1,y-1) + f(x-1,y) + f(x,y) + f(x+1,y) + f(x-1,y+1) + f(x,y+1) + f(x+1,y+1))/9
提示:利用Bitmap类的GetPixel,SetPixel方法对图片的像素进行读取或写入。
代码部分:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace practice17
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
byte[] picturebytes;
Image img;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog file1 = new OpenFileDialog();
file1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file1.Filter = "图片|*.jpg";
file1.Title = "请选择图片";
if (file1.ShowDialog() == DialogResult.OK)
{
string path = file1.FileName;
FileStream fs = new FileStream(path,FileMode.Open);
picturebytes = new byte[fs.Length];
BinaryReader br = new BinaryReader(fs);
picturebytes = br.ReadBytes(Convert.ToInt32(fs.Length));
MemoryStream ms = new MemoryStream(picturebytes);
Bitmap btmp = new Bitmap(fs);
img = btmp;
pictureBox1.Image = img;
}
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(img);
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color RGB = bmp.GetPixel(i, j);
int r = 255 - RGB.R;
int g = 255 - RGB.G;
int b = 255 - RGB.B;
bmp.SetPixel(i, j, Color.FromArgb(r,g,b));
}
}
pictureBox2.Image = bmp;
}
private void button3_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(img);
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color RGB = bmp.GetPixel(i, j);
int r = (RGB.R + RGB.G + RGB.B) / 3;
bmp.SetPixel(i, j, Color.FromArgb(r,r,r));
}
}
pictureBox3.Image = bmp;
}
private void button4_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(img);
int[,] s1 = new int[bmp.Width, bmp.Height];
for (int i = 0; i < bmp.Width-2; i++)
{
for (int j = 0; j < bmp.Height-2; j++)
{
int RGB1 = bmp.GetPixel(i, j + 1).ToArgb();
int RGB2 = bmp.GetPixel(i, j + 2).ToArgb();
int RGB3 = bmp.GetPixel(i + 1, j).ToArgb();
int RGB4 = bmp.GetPixel(i + 1, j + 1).ToArgb();
int RGB5 = bmp.GetPixel(i + 1, j + 2).ToArgb();
int RGB6 = bmp.GetPixel(i + 2, j).ToArgb();
int RGB7 = bmp.GetPixel(i + 2, j + 1).ToArgb();
int RGB8 = bmp.GetPixel(i + 2, j + 2).ToArgb();
int RGB9 = bmp.GetPixel(i, j).ToArgb();
//s1[i, j] = RGB9;
s1[i + 1, j + 1] = (RGB1 + RGB2 + RGB3 + RGB4 + RGB5 + RGB6 + RGB7 + RGB8 + RGB9) / 9;
bmp.SetPixel(i+1, j+1, Color.FromArgb(s1[i+1,j+1]));
}
}
pictureBox4.Image = bmp;
}
}
}
运行结果: