110,533
社区成员
发帖
与我相关
我的任务
分享
private void gray8_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
//curBitmap为我定义的 一个载入图片 为 form的私有成员变量
//新的我要的8位图像容器
Bitmap bit = new Bitmap(curBitmap.Width,curBitmap.Height,PixelFormat.Format8bppIndexed);
//可读写的方式锁定全部原图像
BitmapData data = curBitmap.LockBits(new Rectangle(0, 0, curBitmap.Width,curBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//得到首地址
IntPtr ptr1 = data.Scan0;
//可读写的方式锁定全部容器
BitmapData data2 = bit.LockBits(new Rectangle(0, 0, bit.Width, bit.Height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
//得到首地址
IntPtr ptr2 = data2.Scan0;
//计算24位图像的字节数
int bytes = curBitmap.Width * curBitmap.Height * 3;
//定义位图数组
byte[] grayValues = new byte[bytes];
//复制被锁定的图像到该数组
System.Runtime.InteropServices.Marshal.Copy(ptr1, grayValues, 0, bytes);
//同上
int byte8 = curBitmap.Width * curBitmap.Height;
byte [] gray8Values=new byte[byte8];
System.Runtime.InteropServices.Marshal.Copy(ptr2, gray8Values, 0, byte8);
for (int i = 0,n=0; i < bytes;i+=3 ,n++)
{
//灰度变换
double colorTemp = grayValues[i + 2] * 0.299 + grayValues[i + 1] * 0.589 + grayValues[i] * 0.114;
//这个是测试用的可以忽略 这是原图24位
grayValues[i + 2] = grayValues[i + 1] = grayValues[i] = (byte)colorTemp;
//将灰度值赋值给 容器 这是新图8位
gray8Values[n] = (byte)colorTemp;
}
//送回数组
System.Runtime.InteropServices.Marshal.Copy( gray8Values, 0,ptr2, byte8);
System.Runtime.InteropServices.Marshal.Copy( grayValues, 0,ptr1, bytes);
//解锁
curBitmap.UnlockBits(data);
bit.UnlockBits(data2);
//调色板
ColorPalette palette = bit.Palette;
//调色板结构体数组 填充
for (int i = 0; i != palette.Entries.Length; i++)
{
palette.Entries[i] = Color.FromArgb(i, i, i);//(说实话这步为啥这麽做我也不知道)
}
bit.Palette = palette;
String path2 = System.AppDomain.CurrentDomain.BaseDirectory;
String str = path2 + "bb.jpg";
Bitmap b = bit.Clone(new Rectangle(0, 0, bit.Width, bit.Height), PixelFormat.Format8bppIndexed);
b.Save(@"E:\TEMP\bb.jpg", ImageFormat.Jpeg);// b.Save(@str, ImageFormat.Jpeg);
b.Dispose();
bit.Dispose();
Invalidate();
}
}