搜尋此網誌

2009年5月1日 星期五

C# Image to CSV





















這是一張10x10 pixel的點陣圖,我將它利用Photoshop放大成3200%















這個CSV檔是由上圖所讀取出來的,0代表黑色,255代表白色

以觀念來說這個CSV檔裡的數值是表示最上面那張10x10的圖沒錯

為了好看我用較好理解的寫法實現它,C#寫法如下:

//開啟圖至pictureBox1
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "BMP(*.BMP)|*.bmp|" + "所有檔案|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pictureBox1.Width = Image.FromFile(openFileDialog.FileName).Width;
pictureBox1.Height = Image.FromFile(openFileDialog.FileName).Height;
pictureBox1.Image = Image.FromFile(openFileDialog.FileName);
}
}


因為是黑白影像,這邊我只對R讀取。


private void btnProcess_Click(object sender, EventArgs e)
{
FileStream fw = new FileStream( @"c:\r.csv", FileMode.Open);
StreamWriter sw = new StreamWriter(fw, System.Text.Encoding.Default);
string str;
Bitmap p1 = (Bitmap)pictureBox1.Image;
int[,] r = new int[p1.Height, p1.Width];
int[,] g = new int[p1.Height, p1.Width];
int[,] b = new int[p1.Height, p1.Width];

for (int i = 0; i < p1.Height; i++)
{
for (int j = 0; j < p1.Width; j++)
{
r[i, j] = p1.GetPixel(j, i).R;
if (j < p1.Width )
{
//最後一個值後面不用逗號
if (j == p1.Width -1)
{
str = r[i, j] + "";
sw.Write(str);
}
else
{
str = r[i, j] + ",";
sw.Write(str);
}
}
}
//換行繼續下一個j迴圈寫入
sw.Write('\n');
}
sw.Flush();
fw.Close();
MessageBox.Show("執行完畢");
}





範例檔下載

沒有留言:

張貼留言