使用高效率方法將彩色照片轉成黑白照片
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 image = new ImageForm();
int[, ,] rgb = image.getRGBData_unsafe();
image.doGray(rgb);
image.Show();
}
class ImageForm : Form
{
Image image;
public ImageForm()
{
image = Image.FromFile(@"D:\MyPhoto\IMG_3841.JPG");
this.Text = @"D:\MyPhoto\IMG_3841.JPG";
}
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 int[,,] getRGBData_unsafe()
{
Bitmap bimage = new Bitmap(image);
return getRGBData(bimage);
}
public void doGray(int[,,]rgbData) {
MessageBox.Show("開始進行灰階處理");
// Step 1: 利用 Bitmap 將 image 包起來
Bitmap bimage = new Bitmap(image);
int Height = bimage.Height;
int Width = bimage.Width;
// Step 2:
for (int y = 0; y < Height; y++) {
for (int x = 0; x < Width; x++) {
int gray = (rgbData[x, y, 0] + rgbData[x, y, 1] + rgbData[x, y, 2]) / 3;
bimage.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
}
}
image = bimage;
this.Refresh();
}
public static int[, ,] getRGBData(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;
int Width = bimage.Width;
int[, ,] rgbData = new int[Width, Height, 3];
unsafe {
byte* p = (byte*)(void*)Scan0;
for (int y = 0; y < Height; y++) {
for (int x = 0; x < Width; x++) {
rgbData[x, y, 2] = p[0]; // B
++p;
rgbData[x,y,1]=p[0]; // G
++p;
rgbData[x,y,0]=p[0]; // R
++p;
}
p += ByteOfSkip; // 跳過剩下的 Padding bytes
}
}
bimage.UnlockBits(bmData);
return rgbData;
}
}
}
}
/*
* // 一般處理方式: 灰階化範例
private void button2_Click(object sender, EventArgs e) {
if (CurrentImage != null) {
int[, ,] rgbData = CurrentImage.getRGBData();
CurrentImage.doGray(rgbData);
}
else {
MessageBox.Show("請先載入圖形");
}
}
* public void doGray(int[,,]rgbData) {
MessageBox.Show("開始進行灰階處理");
// Step 1: 利用 Bitmap 將 image 包起來
Bitmap bimage = new Bitmap(image);
int Height = bimage.Height;
int Width = bimage.Width;
// Step 2:
for (int y = 0; y < Height; y++) {
for (int x = 0; x < Width; x++) {
int gray = (rgbData[x, y, 0] + rgbData[x, y, 1] + rgbData[x, y, 2]) / 3;
bimage.SetPixel(x, y, Color.FromArgb(gray, gray, gray));
}
}
image = bimage;
this.Refresh();
MessageBox.Show("灰階處理完成");
}
*/
沒有留言:
張貼留言