🙌

作画資料管理ツールを作りたい #03 ListViewのアイテム(画像ファイル)を選択してプレビューする

に公開
2025/11/26
2件

はじめに

作りたいもの

作画資料管理ツール

  • 画像ファイルをタグで分類できる(pixivやpinterestみたいに)
  • サムネイル一覧できる
  • 選択画像のプレビューができる

↑ここまでで一旦完成

  • 動画も扱う
  • 簡単な画像処理もできる(動画のフレームやトリミングもできたらいいな)
  • LLM?とかで類似画像の検索ができる

↑これは発展

シリーズ記事一覧

https://zenn.dev/indonegiyan/articles/77062311f8755e

前回

  • フォルダ内の画像ファイルをサムネイルで一覧表示する

https://zenn.dev/indonegiyan/articles/6b086be6d324a3

今回

  • 画像ファイル一覧のサムネイルを選択すると、その画像ファイルをプレビューする。

能力

  • 初心者
  • C#とフォームアプリの作り方を勉強する

1. 環境

  • Windows 11 pro
  • Visual Studio Community 2022 (Version 17.14.12)
  • プロジェクトの種類:Windowsフォームアプリ

2. フォームデザイン

主なコントロールと内容

コントロール プロパティ 内容
Form (Name) Form1
TreeView (Name) treeViewDirectory
ListView (Name) listViewThumbnail
View LargeIcon
ImageList (Name) imageListThumbnail
PictureBox (Name) pictureBoxPreview
BackColor Silver



画像ファイル一覧のサムネをクリックまたは方向キーで選択していく。
選択した画像をプレビュー。
選択画像のプレビュー

3. ソースコード

全体のコードは最後にあります。

イベントハンドラ

  1. Form1_Load …前回から変更無し
    TreeViewの最上位にドライブ一覧を構成する。

  2. treeViewDirectory_BeforeExpand …前回から変更無し
    展開ドライブまたはフォルダの配下のフォルダ一覧を構成する。

  3. treeViewDirectory_NodeMouseClick …前回から変更無し
    選択フォルダ内の画像ファイル一覧を作り、サムネイルで表示する。

  4. listViewThumbnail_SelectedIndexChanged …追加
    マウスまたは方向キーでサムネイルを選択していく度に、PictureBoxにプレビュー画像を表示する。
    PictureBoxの領域に合わせて、resizeImg()を呼び出し画像をリサイズする。
    はじめはItemActivateイベントで試したところ、これはクリック操作用みたいだった。
    方向キーで選択アイテムを変更すると反応しなかったので、ひとまずSelectedIndexChangedイベントを使うことにした。

listViewThumbnail_SelectedIndexChanged
//サムネ一覧用リストビューのアイテムを選択したとき
private void listViewThumbnail_SelectedIndexChanged(object sender, EventArgs e)
{
    System.Diagnostics.Debug.WriteLine("■■■listViewThumbnail_SelectedIndexChanged");

    ListView lv = (ListView)sender;

    string filename = lv.FocusedItem.Text;
    string fileFullPath = selectedDir + "\\" + filename;

    pictureBoxPreview.Image = resizeImg(fileFullPath, pictureBoxPreview.Width, pictureBoxPreview.Height);

}

メソッド

  1. resizeImg …変更
    処理自体に変更はないが、メソッド名をmakeThumbnail→resizeImgに変更した。
resizeImg
//リサイズ
private Image resizeImg(string fileFullPath, int width, int height)
{
    System.Diagnostics.Debug.WriteLine($"-- resizeImg -- {fileFullPath}");

    //画像を読み込み
    Image img = Image.FromFile(fileFullPath);

    Bitmap canvas = new Bitmap(width, height);

    using (Graphics g = Graphics.FromImage(canvas))
    {
        g.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);

        //サムネイルのアスペクト調整
        float h = (float)height / (float)img.Height;
        float w = (float)width / (float)img.Width;
        float scale = Math.Min(w, h);
        w = img.Width * scale;
        h = img.Height * scale;

        g.DrawImage(img, (width - w) / 2, (height - h) / 2, w, h);
        //g.DrawImage(isrc, (int)(isrc.Width / scale), (int)(isrc.Height / scale)):
    }

    //画像を破棄
    img.Dispose();

    return (Image)canvas;
}

ソースコード全体

コードが長くなってきたので、ファイルを分割した。

ソースファイル一覧 ※デザイナーやProgramクラス等は省略
プロジェクト名
    ├ Form1.cs
    ├ Image.cs
    ├ Materials.cs
    └ TreeVw.cs

行き当たりばったり開発なので、都度、構成を変える可能性がある。

  • Form1.cs
    主にイベントハンドラでまとめる
Form1.cs
using System;
using System.Windows.Forms;
using System.Xml.Linq;

namespace ImageViewer01
{
    public partial class Form1 : Form
    {

        //選択中のディレクトリ
        string selectedDir;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //ディレクトリのツリー構成
            addTree_Drive();
        }


        //フォルダを展開する直前
        private void treeViewDirectory_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("■■■treeViewDirectory_BeforeExpand");

            if (e.Node != null)
            {
                System.Diagnostics.Debug.WriteLine($"e.Node.Name: {e.Node.Name} ");
                addTree_Child(e.Node); //イベント元のノード(選択したディレクトリ)を渡す
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("e.Node: null ");
            }
        }



        //フォルダをクリック選択したとき(BeforeExpandの後にも呼び出される)
        private void treeViewDirectory_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("■■■treeViewDirectory_NodeMouseClick");

            selectedDir = e.Node.FullPath.Replace("\\\\", "\\"); //ドライブ名の後の「\\」になるので「\」を1つ除去
            makeListThumbs(selectedDir);
        }



        //サムネ一覧用リストビューのアイテムを選択したとき
        private void listViewThumbnail_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("■■■listViewThumbnail_SelectedIndexChanged");

            System.Windows.Forms.ListView lv = (System.Windows.Forms.ListView)sender;
            string filename = lv.FocusedItem.Text; 
            string fileFullPath = selectedDir + @"\\" + filename;

            pictureBoxPreview.Image = resizeImg(fileFullPath, pictureBoxPreview.Width, pictureBoxPreview.Height);
        }
    }
}
  • Image.cs
    画像リサイズなど画像処理でまとめる
Image.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageViewer01
{
    public partial class Form1 : Form
    {
        //リサイズ
        private Image resizeImg(string fileFullPath, int width, int height)
        {
            System.Diagnostics.Debug.WriteLine($"-- resizeImg -- {fileFullPath}");

            //画像を読み込み
            Image img = Image.FromFile(fileFullPath);

            Bitmap canvas = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(canvas))
            {
                g.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);

                //サムネイルのアスペクト調整
                float h = (float)height / (float)img.Height;
                float w = (float)width / (float)img.Width;
                float scale = Math.Min(w, h);
                w = img.Width * scale;
                h = img.Height * scale;

                g.DrawImage(img, (width - w) / 2, (height - h) / 2, w, h);

            }

            //画像を破棄
            img.Dispose();

            return (Image)canvas;
        }

    }
}

  • Materials.cs
    作画資料の一覧用ListView関連をまとめる
Materials.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageViewer01
{
    public partial class Form1 : Form
    {
        //サムネ一覧構成
        private void makeListThumbs(string dir)
        {
            System.Diagnostics.Debug.WriteLine($"-- makeListThumbs --");

            //表示対象のファイル形式
            string[] extensions = { ".jpg", ".jpeg", ".png", ".tif", ".jfif", ".bmp" };

            var itemsFullPath = new List<string>(); //ファイルのフルパス格納用
            try
            {
                itemsFullPath = System.IO.Directory
                                .GetFiles(dir, "*.*")
                                .Where(file => extensions.Any(pattern => file.ToLower()
                                                                    .EndsWith(pattern)
                                                              )
                                      ).ToList();
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine($"例外 -- makeListThumbs ");
                return;
            }

            //サムネイル一覧の初期化
            listViewThumbnail.Items.Clear();
            imageListThumbnail.Images.Clear();

            //ListViewに追加するItem
            var items = new ListViewItem[itemsFullPath.Count];
            // サムネイル用配列
            var images = new Image[itemsFullPath.Count];

            //ImageListに表示するサムネのサイズ
            int width = 50, height = 50;
            imageListThumbnail.ImageSize = new Size(width, height);

            // *** 時間計測用 ************************************
            // Stopwatchクラス生成
            System.Diagnostics.Stopwatch sw = new();
            // 計測開始
            sw.Start();
            // *** 時間計測用 ************************************

            //画像ファイルを1つずつ処理
            for (int i = 0; i < itemsFullPath.Count; i++)
            {
                //フルパスからファイル名のみ抽出
                string fileName = System.IO.Path.GetFileName(itemsFullPath[i]);

                //サムネイル作成→サムネ用配列に格納
                images[i] = resizeImg(itemsFullPath[i], width, height);
                //pictureBox1.Image = images[i];

                //サムネのファイル名追加
                items[i] = new ListViewItem(fileName, i); //ファイル名, イメージインデックスを指定
            }

            // *** 時間計測用 ************************************
            // 計測停止
            sw.Stop();
            // 結果表示
            System.Diagnostics.Debug.WriteLine("*** 計測時間 ***");
            TimeSpan ts = sw.Elapsed;
            System.Diagnostics.Debug.WriteLine($"{ts.Hours}時間 {ts.Minutes}分 {ts.Seconds}秒 {ts.Milliseconds}ミリ秒");
            // *** 時間計測用 ************************************

            //サムネが入った配列をImageListに追加→ListViewのLargeImageListに設定
            imageListThumbnail.Images.AddRange(images);
            listViewThumbnail.LargeImageList = imageListThumbnail;

            //アイテムをサムネ一覧に追加
            listViewThumbnail.Items.AddRange(items);

        }
    }
}

  • TreeVw.cs
    フォルダツリー関連をまとめる
TreeVw.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageViewer01
{
    public partial class Form1 : Form
    {

        //ツリービューにノード(ドライブ名)を追加
        private void addTree_Drive()
        {
            string[] dirveList = Environment.GetLogicalDrives(); //ドライブ名一覧を取得

            foreach (string drive in dirveList)
            {
                // \除去(C:\ → C:)
                //    …をしたが、後のGetDirectories()でうまく取得できないドライブがある
                //string str = drive.Substring(0, drive.Length - 1);
                string str = drive;

                TreeNode tNode = new(str, 0, 0); //ノードにドライブアイコンを設定
                treeViewDirectory.Nodes.Add(tNode); //親ノードにドライブを設定

                //ダミーノード追加
                if (treeViewDirectory.Nodes.Count != 0)
                {
                    tNode.Nodes.Add("...");
                }
            }
        }


        //ツリービューにノード(ディレクトリ名)を追加
        private void addTree_Child(TreeNode treeParent)
        {
            System.Diagnostics.Debug.WriteLine($"-- addTree_Child -- treeParent.FullPath: {treeParent.FullPath}");

            TreeNode treeChild;

            DirectoryInfo dirInfo = new(treeParent.FullPath); //子ディレクトリ一覧を取得(展開する親ディレクトリのフルパスを指定)
            treeParent.Nodes.Clear(); //ダミーノードを消去

            //サブディレクトリのノード追加
            try
            {
                foreach (DirectoryInfo subDir in dirInfo.GetDirectories()) //※光学ドライブだと例外発生
                {
                    treeChild = new TreeNode(subDir.Name, 1, 2);
                    treeParent.Nodes.Add(treeChild);

                    //ダミーノード追加
                    if (treeParent.Nodes.Count != 0)
                    {
                        treeChild.Nodes.Add("...");
                    }
                }
            }
            catch (IOException ex)
            {

                string msg = "!!デバイスの準備ができていません";
                treeChild = new TreeNode(msg, 1, 2);
                treeParent.Nodes.Add(treeChild);
            }

        }

    }
}

参考にさせていただきました

https://dobon.net/vb/dotnet/control/lvpointselection.html

おわり

ここまででひとまず簡易画像ビューワが作れた感じです。検索機能や直接フォルダを開く機能はまだ無いしデザインもできていませんが。
データベース連携あたりを記事にまとめ始めてもいいのですが、あえて一番難しい高速化のところを先に進めるか迷っていいます。理由は、今はまだ実装機能が少なくコード量やDBなど外部連携もないので、あれこれ試行錯誤しても影響が少ないし気にせず作業できるのかなぁと。
果たしで完成できるのだろうか…

Discussion

いぬいぬいぬいぬ

string fileFullPath = selectedDir + @"\" + filename;

Path.Combine()を使うと、パス区切り文字を自動で追加したパスの文字列を作ってくれます。
https://learn.microsoft.com/ja-jp/dotnet/api/system.io.path.combine?view=net-9.0#definition
区切り文字のエンコード忘れや、OSの違い(\か/か)を考えなくて良くなりますよ!

selectedDir = e.Node.FullPath.Replace("\\", "\"); //ドライブ名の後の「\」になるので「\」を1つ除去

Path.GetFullPath()でパスの正規化(不要な\\を削除など)をしてくれます。
https://learn.microsoft.com/ja-jp/dotnet/api/system.io.path.getfullpath?view=net-9.0

例
using System.IO;
var invalidPath = """c:\abc\def\\""";
Console.WriteLine(invalidPath); // c:\abc\def\\
var validPath = Path.GetFullPath(invalidPath);
Console.WriteLine(validPath); // c:\abc\def\
1
焼き肉焼き肉

おお、こんな便利なものがあるのですね。ありがとうございます。試してみます!

1