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 高效率轉黑白
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 高效率影像處理 -- 反轉顏色範例
private void button1_Click(object sender, EventArgs e)
{
ImageForm CurrentImage = new ImageForm();
CurrentImage.Invert();
CurrentImage.Show();
}
class ImageForm : Form
{
Image image;
public ImageForm()
{
image=Image.FromFile(@"D:\MyPhoto\IMG_3841.JPG");
this.Text = @"D:\MyPhoto\IMG_3841.JPG";
}
/*public void LoadImage(String Filename)
{
// Step 1: 載入影像
image = Image.FromFile(Filename);
this.Text = Filename;
// Step 2: 調整視窗的大小
this.Height = image.Height;
this.Width = image.Width;
}*/
protected override void OnPaint(PaintEventArgs e)
{
this.Height = image.Height;
this.Width = image.Width;
e.Graphics.DrawImage(image, 0, 0, image.Width, image.Height);
}
public void Invert()
{
Bitmap bimage = new Bitmap(image);
Invert(bimage);
image = bimage;
this.Refresh ();
}
public static void Invert(Bitmap bimage)
{
// Step 1: 先鎖住存放圖片的記憶體
BitmapData bmData = bimage.LockBits(new Rectangle(0, 0, bimage.Width, bimage.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
int stride = bmData.Stride;
// Step 2: 取得像點資料的起始位址
System.IntPtr Scan0 = bmData.Scan0;
// 計算每行的像點所佔據的byte 總數
int ByteNumber_Width = bimage.Width * 3;
// 計算每一行後面幾個 Padding bytes
int ByteOfSkip = stride - ByteNumber_Width;
// Step 3: 直接利用指標, 更改圖檔的內容
int Height = bimage.Height;
unsafe
{
byte* p = (byte*)(void*)Scan0;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < ByteNumber_Width; x++)
{
p[0] = (byte)(255 - p[0]); // 彩色資料反轉
++p;
}
p += ByteOfSkip; // 跳過剩下的 Padding bytes
}
}
bimage.UnlockBits(bmData);
//return true;
}
}
}
}
沒有留言:
張貼留言