C# 将32位位图转换为8位(颜色和灰度)
我有一个System.Drawing.Bitmap,其C# 将32位位图转换为8位(颜色和灰度),c#,.net,system.drawing,C#,.net,System.drawing,我有一个System.Drawing.Bitmap,其PixelFormat的Format32bppRgb。 我想把这个图像转换成8比特的位图 以下是将32位图像转换为8位灰度图像的代码: public static Bitmap ToGrayscale(Bitmap bmp) { int rgb; System.Drawing.Color c; for (int y = 0; y <
PixelFormat
的Format32bppRgb
。
我想把这个图像转换成8比特的位图
以下是将32位图像转换为8位灰度图像的代码:
public static Bitmap ToGrayscale(Bitmap bmp)
{
int rgb;
System.Drawing.Color c;
for (int y = 0; y < bmp.Height; y++)
for (int x = 0; x < bmp.Width; x++)
{
c = bmp.GetPixel(x, y);
rgb = (int)((c.R + c.G + c.B) / 3);
bmp.SetPixel(x, y, System.Drawing.Color.FromArgb(rgb, rgb, rgb));
}
return bmp;
}
公共静态位图ToGrayscale(位图bmp)
{
int rgb;
系统。绘图。颜色c;
对于(int y=0;y
但是,我最终使用的位图仍然具有Format32bppRgb
的PixelFormat属性
而且
- 如何将32位彩色图像转换为8位彩色图像
谢谢你的意见
相关。
-
-
-
-
-
-必须创建(并返回)位图的新实例
像素格式在位图的构造函数中指定,不能更改
编辑:
示例代码基于:
公共静态位图ToGrayscale(位图bmp){
var result=新位图(bmp.Width、bmp.Height、PixelFormat.format8bppingdexed);
BitmapData data=result.LockBits(新矩形(0,0,result.Width,result.Height)、ImageLockMode.WriteOnly、PixelFormat.Format8Bppined);
//将图像中的字节复制到字节数组中
字节[]字节=新字节[data.Height*data.Stride];
Marshal.Copy(data.Scan0,bytes,0,bytes.Length);
对于(int y=0;y 字节[x*data.Stride+y]=rgb;
}
}
//将字节数组中的字节复制到映像中
Marshal.Copy(字节,0,data.Scan0,字节.长度);
结果:解锁位(数据);
返回结果;
}
谢谢。如果使用PixelFormatFormat8Bppined
创建新位图,则无法使用SetPixel
方法,因为这会导致异常:SetPixel不支持索引像素格式的图像。
bytes[x*data.Stride+y]=rgb。。。步幅不是一排的宽度吗?我想x和y必须交换,但我没有测试它。。。为了澄清一下,应该是bytes[x*data.Height+y]=rgb,否则将因索引超出数组错误而崩溃。可能这“取决于”bytes[y*data.Stride+w]=rgb
对我有用。@匿名-你有很多链接,你现在需要什么?@SimonMourier,我在扔掉赏金后解决了这个问题。所以,我现在什么都不需要。
public static Bitmap ToGrayscale(Bitmap bmp) {
var result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed);
BitmapData data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
// Copy the bytes from the image into a byte array
byte[] bytes = new byte[data.Height * data.Stride];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
for (int y = 0; y < bmp.Height; y++) {
for (int x = 0; x < bmp.Width; x++) {
var c = bmp.GetPixel(x, y);
var rgb = (byte)((c.R + c.G + c.B) / 3);
bytes[x * data.Stride + y] = rgb;
}
}
// Copy the bytes from the byte array into the image
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
result.UnlockBits(data);
return result;
}