10分でできるプログラミング

Visual Studio 2019 Comunity で、.Net Framework を用いてプログラミングします。

ソースコードは、次のとおりです。

using System.Drawing;
using System.Windows.Forms;

namespace 画像結合
{
   public partial class Form1 : Form
   {
       Image 左画像, 右画像, 結合画像;
       PictureBox 左表示, 右表示;
       Button 左ボタン, 右ボタン, 結合;

       public void 左クリック()
       {
           MessageBox.Show("左が押されました");
           OpenFileDialog ファイル読込 = new OpenFileDialog();
           if (ファイル読込.ShowDialog() == DialogResult.OK)
           {
               左画像 = Image.FromFile(ファイル読込.FileName);
               左表示.Image = 左画像;
           }
       }

       public void 右クリック()
       {
           MessageBox.Show("右が押されました");
           OpenFileDialog ファイル読込 = new OpenFileDialog();
           if (ファイル読込.ShowDialog() == DialogResult.OK)
           {
               右画像 = Image.FromFile(ファイル読込.FileName);
               右表示.Image = 右画像;
           }
       }

       public void つなぎます()
       {
           MessageBox.Show("くっつけます");

           int 幅, 高さ;

           幅 = 左画像.Width + 右画像.Width;
           高さ = 左画像.Height;

           if (高さ < 右画像.Height)
           {
               高さ = 右画像.Height;
           }

           結合画像 = new Bitmap(幅, 高さ);

           Graphics g = Graphics.FromImage(結合画像);

           g.DrawImage(左画像, 0, 0, 左画像.Width, 左画像.Height);
           g.DrawImage(右画像, 左画像.Width, 0, 右画像.Width, 右画像.Height);

           SaveFileDialog ファイル保存 = new SaveFileDialog();
           if (ファイル保存.ShowDialog() == DialogResult.OK)
           {
               結合画像.Save(ファイル保存.FileName, System.Drawing.Imaging.ImageFormat.Png);
           }
           g.Dispose();
       }

       public Form1()
       {
           InitializeComponent();

           左ボタン = new Button();
           this.Controls.Add(左ボタン);
           左ボタン.Text = "ひだり";

           右ボタン = new Button();
           this.Controls.Add(右ボタン);
           右ボタン.Text = "みぎ";
           右ボタン.Location = new Point(100, 0);

           左ボタン.Click += (s, e) => 左クリック();
           右ボタン.Click += (s, e) => 右クリック();

           左表示 = new PictureBox();
           this.Controls.Add(左表示);
           左表示.BackColor = Color.LightCyan;
           左表示.Size = new Size(380, 400);
           左表示.Location = new Point(10, 30);

           右表示 = new PictureBox();
           this.Controls.Add(右表示);
           右表示.BackColor = Color.Red;
           右表示.Size = new Size(380, 400);
           右表示.Location = new Point(410, 30);

           結合 = new Button();
           this.Controls.Add(結合);
           結合.Text = "結合";
           結合.Location = new Point(200, 0);

           結合.Click += (s, e) => つなぎます();
       }
   }
}

参考になれば幸いです。

この記事が気に入ったらサポートをしてみませんか?