将24位的彩色图片转化为8位的灰度图片 C#写的。
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;
using System.Diagnostics;
namespace my24to8
{
public partial class Form1 : Form
{
Bitmap curBitmap;
Bitmap bit;
Stopwatch st;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
curBitmap = (Bitmap)Bitmap.FromFile(op.FileName);
pictureBox1.Image = curBitmap;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
st = new Stopwatch();
st.Start();
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * bmpData.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
Rectangle rect2 = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
bit = new Bitmap(curBitmap.Width, curBitmap.Height, PixelFormat.Format8bppIndexed);
System.Drawing.Imaging.BitmapData bmpData2 = bit.LockBits(rect2, System.Drawing.Imaging.ImageLockMode.ReadWrite, bit.PixelFormat);
IntPtr ptr2 = bmpData2.Scan0;
int bytes2 = bmpData2.Stride * bmpData2.Height;
byte[] rgbValues2 = new byte[bytes2];
System.Runtime.InteropServices.Marshal.Copy(ptr2, rgbValues2, 0, bytes2);
double colorTemp = 0;
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width * 3; j += 3)
{
colorTemp = rgbValues[i * bmpData.Stride + j + 2] * 0.299 + rgbValues[i * bmpData.Stride + j + 1] * 0.578 + rgbValues[i * bmpData.Stride + j] * 0.114;
rgbValues2[i * bmpData2.Stride + j / 3] = (byte)colorTemp;
}
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues2, 0, ptr2, bytes2);
curBitmap.UnlockBits(bmpData);
ColorPalette tempPalette;
{
using (Bitmap tempBmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
{
tempPalette = tempBmp.Palette;
}
for (int i = 0; i < 256; i++)
{
tempPalette.Entries[i] = Color.FromArgb(i, i, i);
}
bit.Palette = tempPalette;
}
bit.UnlockBits(bmpData2);
st.Stop();
pictureBox1.Image = bit;
textBox1.Text = st.ElapsedMilliseconds.ToString();
bit.Save(@"D:/aaa.bmp");
}
}
}
}