LoginSignup
0
1

More than 3 years have passed since last update.

[C#/xaml] BitmapSourceやその派生クラスから、System.Drawing.Bitmapに変換する(BmpBitmapEncoderクラス)

Last updated at Posted at 2020-02-25

もくじ
https://qiita.com/tera1707/items/4fda73d86eded283ec4f

Bitmap関連
BitmapSource派生クラスの使い方

やりたいこと

WPFアプリでよく使うBitmapSourceやその派生のBitmapImageRenderTargetBitmapTransformedBitmapSystem.Drawing.Bitmapに変換したい。
(新しく作る処理ではBitmapSourceを使いたいが、もともとあるロジックでSystem.Drawing.Bitmapを使ってるときに、そこに合わせに行きたい)

やり方

BmpBitmapEncoderを使う。

サンプル

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    // BitmapSourceの派生クラス「RenderTargetBitmap」で、画像を取ってくる
    // 「RouletteWhole」は、Gridの名前。
    var canvas = new RenderTargetBitmap((int)RouletteWhole.ActualWidth, (int)RouletteWhole.ActualHeight, 96, 96, PixelFormats.Pbgra32);
    canvas.Render(RouletteWhole);

    // BmpBitmapEncoderに画像を入れる
    using (var stream = new MemoryStream())
    {
        BitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(canvas));
        encoder.Save(stream);

        // BmpBitmapEncoderからSystem.Drawing.Bitmapをつくる
        var bitmap = new System.Drawing.Bitmap(stream);
        bitmap.Save(@".\aaa.bmp");
    }
}

参考

Convert RenderTargetBitmap to Bitmap
https://stackoverflow.com/questions/20083210/convert-rendertargetbitmap-to-bitmap

親クラスの「BitmapEncoder」クラス
https://docs.microsoft.com/ja-jp/dotnet/api/system.windows.media.imaging.bitmapencoder?view=netframework-4.8

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1