It’s just for my memo.
using System;
using System.Windows;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
namespace WritableBitmap
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WriteableBitmap srcWritableBitmap;
WriteableBitmap destWritableBitmap;
private void button1_Click(object sender, RoutedEventArgs e)
{
LoadImage();
Process();
}
float[,] filter = {
{ 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f },
{ 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f },
{ 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f },
{ 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f },
{ 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f, 1 / 25f }
};
private void Process()
{
int width = srcWritableBitmap.PixelWidth;
int height = srcWritableBitmap.PixelHeight;
int bytesPerPixel = srcWritableBitmap.Format.BitsPerPixel / 8;
int srcPtr = (int)srcWritableBitmap.BackBuffer;
int destPtr = (int)destWritableBitmap.BackBuffer;
for (int y = 2; y < height-2; y++)
for (int x = 2; x < width-2; x++)
for (int col = 0; col < bytesPerPixel; col++)
{
int destIndex = destPtr + width * bytesPerPixel * y + bytesPerPixel * x + col;
if (y < height/3 || y > (height/3)*2)
{
float v = 0f;
for (int yy = -2; yy <= 2; yy++)
for (int xx = -2; xx <= 2; xx++)
{
int srcIndex = srcPtr + width * bytesPerPixel * (y + yy) + bytesPerPixel * (x + xx) + col;
float filterValue = filter[yy + 2, xx + 2];
unsafe
{
v = v + (*((byte*)srcIndex) * filterValue);
}
}
v = Math.Abs(v);
v = (v > 255) ? 255 : v;
unsafe
{
*((byte*)destIndex) = (byte)v;
}
}
else
{
int srcIndex = srcPtr + width * bytesPerPixel * y + bytesPerPixel * x + col;
unsafe
{
*((byte*)destIndex) = *((byte*)srcIndex);
}
}
}
resultImage.Source = destWritableBitmap;
}
private void LoadImage()
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = “Bitmap files|*.bmp;*.png;*.jpeg;*.jpg;*.gif;*.tiff;*.tif;*.wdp|” +
“BMP files (*.bmp)|*.bmp|” +
“PNG files (*.png)|*.png|” +
“JPEG files (*.jpeg, *.jpg)|*.jpeg;*.jpg|” +
“GIF files (*.gif)|*.gif|” +
“TIFF files (*.tiff, *.tif)|*.tiff;*.tif|” +
“Windows Media Player files (*.wdp)|*.wdp|” +
“All files (*.*)|*.*”;
if ((bool)dlg.ShowDialog())
{
srcImage.Source = null;
srcWritableBitmap = null;
BitmapFrame frame = null;
try
{
frame = BitmapFrame.Create(new Uri(dlg.FileName), BitmapCreateOptions.None,
BitmapCacheOption.None);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, Title);
return;
}
srcWritableBitmap = new WriteableBitmap(frame);
if (srcWritableBitmap.Format.BitsPerPixel != 8 &&
srcWritableBitmap.Format.BitsPerPixel != 24 &&
srcWritableBitmap.Format.BitsPerPixel != 32)
{
MessageBox.Show(“Bitmap must have 8 or 24 bits or 32 bits per pixel”, Title);
srcWritableBitmap = null;
return;
}
srcImage.Source = srcWritableBitmap;
destWritableBitmap = srcWritableBitmap.Clone();
}
}
}
}
コメントを残す