这里之所以说“浅谈”是因为我这里只是简单的介绍如何使用Visual C#进行图像的读入、保存以及对像素的访问。而不涉及太多的算法。
一、读取图像
在Visual C#中我们可以使用一个Picture Box控件来显示图片,如下:
private void btnOpenImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
//pbxShowImage.ImageLocation = ofd.FileName;
bmp = new Bitmap(ofd.FileName);
if (bmp==null)
{
MessageBox.Show("加载图片失败!", "错误");
return;
}
pbxShowImage.Image = bmp;
ofd.Dispose();
}
}
</div>
其中bmp为类的一个对象:private Bitmap bmp=null;
在使用Bitmap类和BitmapData类之前,需要使用using System.Drawing.Imaging;
二、保存图像
private void btnSaveImage_Click(object sender, EventArgs e)
{
if (bmp == null) return;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "BMP Files(*.bmp)|*.bmp|JPG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|All Files(*.*)|*.*";
if (sfd.ShowDialog() == DialogResult.OK)
{
pbxShowImage.Image.Save(sfd.FileName);
MessageBox.Show("保存成功!","提示");
sfd.Dispose();
}
}
</div>
三、对像素的访问
我们可以来建立一个GrayBitmapData类来做相关的处理。整个类的程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace ImageElf
{
class GrayBitmapData
{
public byte[,] Data;//保存像素矩阵
public int Width;//图像的宽度
public int Height;//图像的高度
public GrayBitmapData()
{
this.Width = 0;
this.Height = 0;
this.Data = null;
}
public GrayBitmapData(Bitmap bmp)
{
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
this.Width = bmpData.Width;
this.Height = bmpData.Height;
Data = new byte[Height, Width];
unsafe
{
byte* ptr = (byte*)bmpData.Scan0.ToPointer();
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
//将24位的RGB彩色图转换为灰度图
int temp = (int)(0.114 * (*ptr++)) + (int)(0.587 * (*ptr++))+(int)(0.299 * (*ptr++));
Data[i, j] = (byte)temp;
}
ptr += bmpData.Stride - Width * 3;//指针加上填充的空白空间
}
}
bmp.UnlockBits(bmpData);
}
public GrayBitmapData(string path)
: this(new Bitmap(path))
{
}
public Bitmap ToBitmap()
{
Bitmap bmp=new Bitmap(Width,Height,PixelFormat.Format24bppRgb);
BitmapData bmpData=bmp.LockBits(new Rectangle(0,0,Width,Height),ImageLockMode.WriteOnly,PixelFormat.Format24bppRgb);
unsafe
{
byte* ptr=(byte*)bmpData.Scan0.ToPointer();
for(int i=0;i<Height;i++)