Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9699

【C#】ListViewを用いて特定のフォルダー内に散らばった画像を表示する

$
0
0

環境

  • OS:Windows10Pro
  • IDE:VisualStadio2019

どんなものを作りたいのか

フォルダ
├フォルダ
 └画像
├フォルダ
 └画像
├フォルダ
 └画像

のように散らばった画像を一覧表示するもの

手順

プロジェクトの作成

下記の画像のものを選択する。
image.png

プロジェクト名等を適当に決めて作成する。
image.png

レイアウトの作成

自分が必要だと思う機能を盛り込んでレイアウトを考える。

image.png

コーディング

各オブジェクトに任意の機能をつけ足していく
細かい機能はgithubに載せているコードを見てほしい。

表示ボタンのソースコード

private void button2_Click(object sender, EventArgs e)
        {
            listView1.Clear();
            string extension = "*." + textBox1.Text;
            string imageDir = this.path; // 画像ディレクトリ
            string[] jpgFiles = Directory.GetFiles(imageDir, extension, SearchOption.AllDirectories);

            int width = 100;
            int height = 80;

            imageList1.ImageSize = new Size(width, height);
            listView1.LargeImageList = imageList1;

            for (int i = 0; i < jpgFiles.Length; i++)
            {
                Image original = Bitmap.FromFile(jpgFiles[i]);
                Image thumbnail = createThumbnail(original, width, height);

                imageList1.Images.Add(thumbnail);
                listView1.Items.Add(jpgFiles[i], i);

                original.Dispose();
                thumbnail.Dispose();
            }
        }

上記のコードで呼び出されているfunction

Image createThumbnail(Image image, int w, int h)
        {
            Bitmap canvas = new Bitmap(w, h);

            Graphics g = Graphics.FromImage(canvas);
            g.FillRectangle(new SolidBrush(Color.White), 0, 0, w, h);

            float fw = (float)w / (float)image.Width;
            float fh = (float)h / (float)image.Height;

            float scale = Math.Min(fw, fh);
            fw = image.Width * scale;
            fh = image.Height * scale;

            g.DrawImage(image, (w - fw) / 2, (h - fh) / 2, fw, fh);
            g.Dispose();

            return canvas;
        }
'''


Viewing all articles
Browse latest Browse all 9699

Trending Articles