我试图创建一个真正的灰度图像,但是当我的设计师检查文件时,他说图像仍然是RGB。
到目前为止,我尝试了两种方法:
1)使用MakeGrayScale3方法:
public static Image MakeGrayscale3(Image original)
{
//create a blank bitmap the same size as original
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
newBitmap.SetResolution(original.HorizontalResolution, original.VerticalResolution);
//get a graphics object from the new image
Graphics g = Graphics.FromImage(newBitmap);
//create the grayscale ColorMatrix
ColorMatrix colorMatrix = new ColorMatrix(
new float[][]
{
new float[] {.3f, .3f, .3f, 0, 0},
new float[] {.59f, .59f, .59f, 0, 0},
new float[] {.11f, .11f, .11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
//create some image attributes
ImageAttributes attributes = new ImageAttributes();
//set the color matrix attribute
attributes.SetColorMatrix(colorMatrix);
//draw the original image on the new image
//using the grayscale color matrix
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
//dispose the Graphics object
g.Dispose();
return newBitmap;
}
2)将ImageMagick.Net库与此代码一起使用:
using (MagickImage image = new MagickImage(file))
{
image.ColorSpace = ColorSpace.GRAY;
image.Write(originalFile);
}
如果有人之前遇到过这个问题,或者想知道如何改变这个问题......
谢谢!
原始图片:
结果图像(ImageMagick):
结果图像(MakeGrayscale3):
答案 0 :(得分:1)
jpeg使用的灰度格式在经典System.Drawing
类中不可用。但是,它可以在System.Windows.Media
中找到。您需要添加PresentationCore
和WindowsBase
作为使用它们的参考。
public static void SaveAsGrayscaleJpeg(String loadPath, String savePath)
{
using (FileStream fs = new FileStream(savePath, FileMode.Create))
{
BitmapSource img = new BitmapImage(new Uri(new FileInfo(loadPath).FullName));
FormatConvertedBitmap convertImg = new FormatConvertedBitmap(img, PixelFormats.Gray8, null, 0);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(convertImg));
encoder.Save(fs);
}
}
作为奖励,这会自动进行灰度转换。
如果您实际上是从Image
/ Bitmap
课程开始,则可以some solutions around进行转换。
答案 1 :(得分:1)
感谢所有答案,但在阅读了汉斯在那里提到的主题后,他们谈到了我用来解决问题的FreeImageNET库。
使用此代码,我设法将图像保存为灰度图像:
FreeImageAPI.FreeImage.ConvertTo8Bits(newimg)
答案 2 :(得分:0)
问题是这一行:
Bitmap newBitmap = new Bitmap(original.Width, original.Height);
如果你看MSDN page它说:
此构造函数创建一个PixelFormat枚举值为 Format32bppArgb 的Bitmap。
因此,您只是创建另一个彩色图像。您需要做的是使用a different constructor强制使用其他格式:
Bitmap newBitmap = new Bitmap( original.Width, original.Height,
PixelFormat.Format8bppIndexed );
但是那会给你另一个问题 - 你可以使用Graphics
对象绘制具有该像素格式的位图。有一个PixelFormat.Format16bppGrayScale
似乎工作得更少。
所以,我的建议是手动。使用LockBits可以访问原始位图并自行进行转换。这是一个更多的工作(即你不能使用ColorMatrix
的东西,你必须注意检查源位图是24位还是32位),但它会工作得很好
需要注意的一个问题是,它不是真正的"灰度格式,它的8位索引。所以你还必须创建一个调色板。简单地将256个值中的每一个映射到相同的值,即0 - > 0,100 - > 100,255 - > 255。