Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

もくじ
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

tera1707
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away