ピクチャフォルダの画像ファイルのサムネイル表示します。
サムネイルは何度か記事にしていますが、今回はWPF+コードビハインドで、できる限りコード量を少ないサンプルコードにしてみました。
ソースコード
ファイル名:ThumSample06.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
ファイル名:MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;
namespace ThumSample06;
public partial class MainWindow : Window
{
public ObservableCollection<ImageItem> Images { get; set; } = [];
public MainWindow()
{
InitializeComponent();
ThumbnailListView.ItemsSource = Images;
// 適宜パスを変更(例: デスクトップの画像フォルダなど)
string targetFolder = @"C:\Users\karet\Pictures";
LoadImages(targetFolder);
}
private void LoadImages(string folderPath)
{
if (!Directory.Exists(folderPath)) return;
string[] imageFiles = Directory.GetFiles(folderPath, "*.*") ?? [];
string[] extensions = { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };
foreach (string file in imageFiles)
{
if (Array.Exists(extensions, ext => file.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
{
try
{
BitmapImage thumb = new ();
thumb.BeginInit();
thumb.UriSource = new Uri(file);
thumb.DecodePixelWidth = 256; // サムネイルサイズ
thumb.CacheOption = BitmapCacheOption.OnLoad;
thumb.EndInit();
thumb.Freeze(); // UIスレッド外でも使用可
Images.Add(new ImageItem
{
FilePath = file,
FileName = Path.GetFileName(file),
Thumbnail = thumb
});
}
catch
{
// 壊れた画像などは無視
}
}
}
}
}
public class ImageItem
{
public string FilePath { get; set; } = "";
public string FileName { get; set; } = "";
public BitmapImage? Thumbnail { get; set; }
}
ファイル名:MainWindow.xaml
<Window x:Class="ThumSample06.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ThumSample06"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<ListView Name="ThumbnailListView"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5" Width="256">
<Image Source="{Binding Thumbnail}" Width="256" Height="256" Stretch="Uniform" />
<TextBlock Text="{Binding FileName}" TextAlignment="Center" TextWrapping="Wrap" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
実行イメージ
画像ファイルがサムネイル表示され、件数が多いとスクロールすることが出来ます。




コメント