0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

BitmapSource派生クラスの使い方

Posted at

#概要
ざっくりBitmapSource派生クラスの使い方。

BitmapImageクラス

ファイルなどから画像を引っ張ってくるときに使う。

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.FilterIndex = 1;
    openFileDialog.Filter = "Jpeg ファイル(.jpg)|*.jpg|All Files (*.*)|*.*";
    bool? result = openFileDialog.ShowDialog();

    if (result != false)
    {
        tb_FileName.Text = openFileDialog.FileName;
        var uri = new Uri(tb_FileName.Text, UriKind.Absolute);
        var image = new BitmapImage(uri);
        MyImage.Source = image;
    }
}

RenderTargetBitmapクラス

UI部品(FlameworkElement)を画像として取り込むときに使う

private void Button_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.FilterIndex = 1;
    saveFileDialog.Filter = "Jpeg ファイル(.jpg)|*.jpg|All Files (*.*)|*.*";
    bool? result = saveFileDialog.ShowDialog();

    if (result == true)
    {
        var canvas = new RenderTargetBitmap((int)MyCanvas.Width, (int)MyCanvas.Height, 96, 96, PixelFormats.Pbgra32);
        canvas.Render(MyCanvas);

        var jpg = new JpegBitmapEncoder();
        jpg.Frames.Add(BitmapFrame.Create(canvas));
        using (Stream stm = File.Create(saveFileDialog.FileName))
        {
            jpg.Save(stm);
        }
    }
}

TransformedBitmapクラス

各種Transform派生クラスと組み合わせて、回転、拡大等するときに使う

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.FilterIndex = 1;
    saveFileDialog.Filter = "Jpeg ファイル(.jpg)|*.jpg|All Files (*.*)|*.*";
    bool? result = saveFileDialog.ShowDialog();

    if (result == true)
    {
        // 画像を取ってきて
        var canvas = new RenderTargetBitmap((int)MyCanvas.Width, (int)MyCanvas.Height, 96, 96, PixelFormats.Pbgra32);
        canvas.Render(MyCanvas);

        // 1/2にタテヨコ縮小して
        var sct = new ScaleTransform(0.5, 0.5);
        var canvas2 = new TransformedBitmap(canvas, sct);

        // 90度回転して
        var rtt = new RotateTransform(90);
        var canvas3 = new TransformedBitmap(canvas2, rtt);

        // 保存する
        var jpg = new JpegBitmapEncoder();
        jpg.Frames.Add(BitmapFrame.Create(canvas3));
        using (Stream stm = File.Create(saveFileDialog.FileName))
        {
            jpg.Save(stm);
        }
    }
}

コード

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?