2013/04/06

C#.Net 改變影像像素顏色

二年級因為學長程式畫質有點差,想做優化
找了系上某位老師討論如何優化,他告訴我必須先有影像基礎以及如何將黑轉白白轉黑實做出來

那時候我大概就放棄了,畢竟得耗費更多時間在上頭
而且影像辨識不是我的擅長領域,突然想到這件事情就來實做吧

首先用小畫家開個2*2的影像,再來將圖片點成對角線白與黑




我的方法就是判斷Argb為相同值,如果是就將其顏色對換成另一種顏色

改變前

改變後



using System;
using System.Drawing;
using System.Windows.Forms;

namespace Change_Image
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button_ReadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "PNG|*.png";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.pictureBox1.Image = Image.FromFile(dialog.FileName);
            }
        }

        private void button_ChageImage_Click(object sender, EventArgs e)
        {
            if (this.pictureBox1.Image != null)
            {
                Bitmap image = new Bitmap(this.pictureBox1.Image);

                for (int width = 0; width < image.Width; width++)
                {
                    for (int heigth = 0; heigth < image.Height; heigth++)
                    {
                        Color color = image.GetPixel(width, heigth);
                        if (color.ToArgb() == Color.Black.ToArgb())
                        {
                            image.SetPixel(width, heigth, Color.White);
                        }
                        else if (color.ToArgb() == Color.White.ToArgb())
                        {
                            image.SetPixel(width, heigth, Color.Black);
                        }
                    }
                }
                this.pictureBox1.Image = image;
            }
        }
    }
}

參考資料:
http://www.dotblogs.com.tw/junegoat/archive/2012/08/15/c-sharp-filter-lockbits-make-stone-like.aspx
http://blog.526net.com/?p=2258