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 = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bmpdata= bitmap.LockBits(rect, ImageLockMode.ReadWrite,bitmap.PixelFormat); byte* pix = (byte*)bmpdata.Scan0; if (bitmap.PixelFormat==PixelFormat.Format8bppIndexed) //是否为灰度图 { for (int i = 0; i < bmpdata.Height; i++) { for (int j = 0; j < bmpdata.Width; j++) { pix[0] = (byte)(255 - pix[0]); //反色 pix++; } } } else { for (int i = 0; i < bmpdata.Height;i++ ) { for (int j = 0; j < bmpdata.Width;j++ ) { pix[0] = (byte)(255 - pix[0]); //反色 pix[1] = (byte)(255 - pix[1]); pix[2] = (byte)(255 - pix[2]); pix = pix + 3; } } } bitmap.UnlockBits(bmpdata); pictureBox2.Image=bitmap; } } }
时间: 2024-10-13 12:30:10