我做了一个自动图像阈值处理功能,并想将其保存为位图文件。
但是,当我使用C#GDI +Bitmap.Save
函数时,尽管我将ImageFormat设置为BMP,但它始终是RGB彩色图像文件,而不是位图图像文件。
我必须将其保存为打印机的位图图像文件,才能读取位图图像文件。
也许您会问我什么是位图图像文件。我不是图像处理专家,对此感到抱歉,很难解释清楚。但我可以举一个例子:在Photoshop中,有几种颜色模式,例如RGB模式/ CMYK模式/索引模式/灰度模式/位图模式,我想将图像保存为C#中的位图模式。
位图模式使用两个颜色值(黑色或白色)之一来表示图像中的像素。位图模式下的图像称为位图1位图像,因为它们的位深度为1。
我用谷歌搜索,但对此一无所获。如何在C#中做到这一点?谢谢。
这是我的代码:
Thread T = new Thread(() => {
Bitmap processedBitmap = new Bitmap(@"G:\\0001.jpg");
BitmapData bitmapData = processedBitmap.LockBits(new Rectangle(0, 0, processedBitmap.Width, processedBitmap.Height), ImageLockMode.ReadWrite, processedBitmap.PixelFormat);
int bytesPerPixel = Bitmap.GetPixelFormatSize(processedBitmap.PixelFormat) / 8;
int byteCount = bitmapData.Stride * processedBitmap.Height;
byte[] pixels = new byte[byteCount];
IntPtr ptrFirstPixel = bitmapData.Scan0;
Marshal.Copy(ptrFirstPixel, pixels, 0, pixels.Length);
int heightInPixels = bitmapData.Height;
int widthInBytes = bitmapData.Width * bytesPerPixel;
for (int y = 0; y < heightInPixels; y++)
{
int currentLine = y * bitmapData.Stride;
for (int x = 0; x < widthInBytes; x = x + bytesPerPixel)
{
int oldBlue = pixels[currentLine + x];
int oldGreen = pixels[currentLine + x + 1];
int oldRed = pixels[currentLine + x + 2];
double averageColor = (oldBlue + oldGreen + oldRed) / 3;
int NewC;
if (averageColor > 200)
{
NewC = 255;
}
else
{
NewC = 0;
}
// calculate new pixel value
pixels[currentLine + x] = (byte)NewC;
pixels[currentLine + x + 1] = (byte)NewC;
pixels[currentLine + x + 2] = (byte)NewC;
}
}
// copy modified bytes back
Marshal.Copy(pixels, 0, ptrFirstPixel, pixels.Length);
processedBitmap.UnlockBits(bitmapData);
processedBitmap.Save("G:\\aaa.bmp", ImageFormat.Bmp);
MessageBox.Show("Sucess!");
});
T.Start();
我相信OP指的是此Adobe链接中的最后一种图像类型。位图仅是数据的容器,所存储数据的格式由PixelFormat设置定义。可以看出,“ Adobe”位图模式是2色格式模式,对应于C#位图中的PixelFormat.Format1bppIndexed。
您有几个将PixelFormat作为参数的位图构造函数。
public Bitmap (int width, int height, System.Drawing.Imaging.PixelFormat format);
public Bitmap (int width, int height, int stride, System.Drawing.Imaging.PixelFormat format, IntPtr scan0);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句