HeyCHのブログ

慢性疲労のへいちゃんです

【C#】PictureBoxに画像を表示しよう

Formに画像を表示したい場合、PictureBoxというコントロールを使用すれば簡単に表示することができます。

PictureBox表示用のプロジェクト作成

  • 新しいプロジェクトの作成>Windows フォームアプリケーション>作成

f:id:HeyCH:20200409000240p:plain
f:id:HeyCH:20200409000253p:plain
f:id:HeyCH:20200409000307p:plain

TextBoxとPictureBoxを配置

f:id:HeyCH:20200409000403p:plain

  • TextBoxのAnchorプロパティを設定

f:id:HeyCH:20200409000609p:plain

  • PictureBoxのAnchorプロパティを設定

f:id:HeyCH:20200409000720p:plain

  • TextBoxにKeyUpイベントを設定

f:id:HeyCH:20200409000948p:plain

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                pictureBox1.Image = Image.FromFile(textBox1.Text);
            }
        }

このようにするとデスクトップ等のローカルファイルをPictureBoxに表示することができます。
f:id:HeyCH:20200409001717p:plain

URLの画像をPictureBoxに表示したい

Web上の画像を表示したい場合は、WebClientを使ってダウンロードしたものを表示します。
以下はファイルが存在する場合ローカルファイルをhttpで始まる文字列の場合ダウンロードして画像を表示しています。

using System.IO;
using System.Net;

namespace WindowsFormsApp3 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                if (File.Exists(textBox1.Text)) {
                    pictureBox1.Image = Image.FromFile(textBox1.Text);
                } else if (textBox1.Text.StartsWith("http")) {
                    using (var wc = new WebClient()) {
                        using (var stream = wc.OpenRead(textBox1.Text)) {
                            pictureBox1.Image = Image.FromStream(stream);
                        }
                    }
                }
            }
        }
    }
}

また、しれっと使ってますが、以下のようなusingは「System.IO」と「System.Net」の名前空間を使用しますという宣言です。
例えば「WebClient」は正確には「System.Net.WebClient」で、「System.Net」を省略することができます。

using System.IO;
using System.Net;

また、以下のようなusingはこの範囲内だけで使用しますという感じの意味です。
本来なら、WebClientおよびStreamはClose()メソッドを呼び出さないとだめなのですが、省略できます。

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                if (File.Exists(textBox1.Text)) {
                    pictureBox1.Image = Image.FromFile(textBox1.Text);
                } else if (textBox1.Text.StartsWith("http")) {
                    using (var wc = new WebClient()) {
                        using (var stream = wc.OpenRead(textBox1.Text)) {
                            pictureBox1.Image = Image.FromStream(stream);
                        }
                    }
                }
            }
        }

もっと簡単に書けないの?

実は以下のようにすごく簡単に書くことができます。

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Enter) {
                pictureBox1.ImageLocation = textBox1.Text;
            }
        }