【C#学习笔记】图片像素操作

时间:2020-12-31 07:37:33
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;

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

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dig = new OpenFileDialog();
            if (dig.ShowDialog() == DialogResult.OK)
                pictureBox1.Image = Image.FromFile(dig.FileName);
        }

        unsafe private void button2_Click(object sender, EventArgs e)
        {

            Bitmap bitmap =(Bitmap)pictureBox1.Image.Clone();   //创建副本,避免操作原图像
            Rectangle rect = , , bitmap.Width, bitmap.Height);
            BitmapData bmpdata= bitmap.LockBits(rect, ImageLockMode.ReadWrite,bitmap.PixelFormat);

            byte* pix = (byte*)bmpdata.Scan0;
            if (bitmap.PixelFormat==PixelFormat.Format8bppIndexed)  //是否为灰度图
            {
                ; i < bmpdata.Height; i++)
                {
                    ; j < bmpdata.Width; j++)
                    {
                        pix[] = ( - pix[]);      //反色
                        pix++;
                    }
                }
            }
            else
            {
                ; i < bmpdata.Height;i++ )
                {
                    ; j < bmpdata.Width;j++ )
                    {
                        pix[] = ( - pix[]);      //反色
                        pix[] = ( - pix[]);
                        pix[] = ( - pix[]);
                        pix = pix + ;
                    }
                }
            }

            bitmap.UnlockBits(bmpdata);
            pictureBox2.Image=bitmap;
        }
    }
}