110,572
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
String filename;
public int height, width;
public int[,] data;
Bitmap input;
private void 開啟ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
filename = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(filename);
input = new Bitmap(filename);
height = input.Height;
width = input.Width;
int[,] data = new int[height,width];
/*利用記憶體Lock方式讀取圖片(比 GetPixel 快許多)*/
Bitmap bmpOut = new Bitmap(width, height, PixelFormat.Format24bppRgb);
BitmapData dataIn = input.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
BitmapData dataOut = bmpOut.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//在C#下,用指摽必須先宣告一段unsafe,在此範圍內才可用指標。
unsafe
{
byte* pIn = (byte*)(dataIn.Scan0.ToPointer());
byte* pOut = (byte*)(dataOut.Scan0.ToPointer());
for (int y = 0; y < dataIn.Height; y++)
{
for (int x = 0; x < dataIn.Width; x++)
{
data[x, y] = pIn[0];
data[x, y] = pIn[0];
data[x, y] = pIn[0];
pOut[0] = (byte)data[x, y];
pOut[1] = (byte)data[x, y];
pOut[2] = (byte)data[x, y];
pIn += 3;
pOut += 3;
}
pIn += dataIn.Stride - dataIn.Width * 3;
pOut += dataOut.Stride - dataOut.Width * 3;
}
}
bmpOut.UnlockBits(dataOut);
input.UnlockBits(dataIn);
pictureBox1.Image = bmpOut;
}
}