プロジェクトの作成
ソースコード
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WPFLibA;
public class Class1
{
public static void Bgr32ToGray(string srcFile, string dstFile)
{
using var inputStream = new FileStream(srcFile, FileMode.Open, FileAccess.Read);
var img = new BitmapImage();
img.BeginInit();
img.CreateOptions = BitmapCreateOptions.None;
img.CacheOption = BitmapCacheOption.OnLoad;
img.StreamSource = inputStream;
img.EndInit();
img.Freeze();
int w = (int)img.PixelWidth;
int h = (int)img.PixelHeight;
int stride = (w * img.Format.BitsPerPixel + 7) / 8;
int ch = img.Format.BitsPerPixel / 8;
int bufSize = stride * h;
byte[] inputBuf = new byte[bufSize];
byte[] outputBuf = new byte[w * h];
img.CopyPixels(inputBuf, stride, 0);
for(int y = 0; y < h; y++)
{
for(int x = 0; x < w; x++)
{
int i = (stride * y) + (x * ch);
int j = w * y + x;
int avg = 0;
for (int k = 0; k < ch; k++)
{
avg += inputBuf[i + k];
}
avg = avg / ch;
outputBuf[j] = (byte)avg;
}
}
BitmapSource result = BitmapSource.Create(
w,
h,
img.DpiX,
img.DpiY,
PixelFormats.Gray8,
BitmapPalettes.Gray256,
outputBuf,
w
);
using var outputStream = new FileStream(dstFile, FileMode.Create, FileAccess.Write);
var encoder = new PngBitmapEncoder();
var frame = BitmapFrame.Create(result);
encoder.Frames.Add(frame);
encoder.Save(outputStream);
}
}
ファイル名:WPFLibA.Console\Program.cs
using WPFLibA;
public class Program1
{
static void Main()
{
string colorFile = @"H:\Pictures\202307131103.PNG";
string grayFile = @"H:\csharp\WPFLibA.Console\output.png";
Class1.Bgr32ToGray(colorFile, grayFile);
}
}
コメント