WPFヘルパー:ImageConverter.cs ー BitmapSourceとImageBufferを相互変換

コンピュータ

WPFのBitmapSourceとImageBufferを相互変換するヘルパー
ImageConverter.cs

using System.Windows.Media;
using System.Windows.Media.Imaging;

using ImageBuffer = Maywork.WPF.Helpers.ImageBufferHelper.ImageBuffer;

namespace Maywork.WPF.Helpers;

public static partial class ImageConverter
{
    // BitmapSourceからImageBuffer変換
    public static ImageBuffer FromBitmapSource(this BitmapSource bmp)
    {
        int width = bmp.PixelWidth;
        int height = bmp.PixelHeight;

        int channels = bmp.Format.BitsPerPixel switch
        {
            8  => 1,
            24 => 3,
            32 => 4,
            _  => throw new NotSupportedException(bmp.Format.ToString())
        };

        int stride = (width * bmp.Format.BitsPerPixel + 7) / 8;

        byte[] pixels = new byte[stride * height];
        bmp.CopyPixels(pixels, stride, 0);

        return new ImageBuffer(width, height, stride, channels, pixels);
    }
     public static ImageBuffer ToBuffer(this BitmapSource bmp)
        => FromBitmapSource(bmp);

    // ImageBufferからBitmapSourceへ変換
    public static BitmapSource ToBitmapSource(this ImageBuffer img)
    {
        PixelFormat format = img.Channels switch
        {
            1 => PixelFormats.Gray8,
            3 => PixelFormats.Bgr24,
            4 => PixelFormats.Bgra32,
            _ => throw new NotSupportedException($"Channels: {img.Channels}")
        };

        var bmp = BitmapSource.Create(
            img.Width,
            img.Height,
            96,                 // dpiX
            96,                 // dpiY
            format,
            null,
            img.Pixels,
            img.Stride);

        bmp.Freeze();

        return bmp;
    }
}

/*

// 使用例

using Maywork.WPF.Helpers;
using ImageBuffer = Maywork.WPF.Helpers.ImageBufferHelper.ImageBuffer;

string file = @"sample.png";

var src = ImageHelper.Load(file);

var buff = ImageConverter.FromBitmapSource(src);
if (buff.Channels > 1)
    buff = ImageBufferHelper.SplitChannels(buff)[0];

Image1.Source = ImageConverter.ToBitmapSource(buff);

*/
Download

コメント