C#WPFでスクショフォルダを監視・画像256色減色・Base64変換・クリップボードへ・HTMLとして貼り付けるツール

コンピュータ

フォルダの監視を試して見ました。
スクリーンショットフォルダを監視し、新しいファイルが出来上がることをトリガーとし、画像を256色に減色しBase64で文字列に変換、HTMLタグを付与しクリップボードへセットするツールになっています。

以下、Base64で貼り付けたイメージ画像

image

幅、高さは778×542で、オリジナルのPNGファイルは45KB、256色に減色しBase64化した文字数が,25,500文字で25KB。
256色に減色しましたが、それなりに見れる画像だと思います。
ただ、HTMLのソースコード上の文字数が大変なことになっています.

ファイル名:ScreenshotWatcher01.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
    <StartUP>ScreenShotWatcher01.App</StartUP>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Magick.NET-Q8-AnyCPU" Version="14.6.0" />
  </ItemGroup>

</Project>

ファイル名:App.xaml.cs


using System.Windows;

namespace ScreenshotWatcher01;

public partial class App : Application
{
    [STAThread]
    public static void Main()
    {
        var app = new App();
        var window = new MainWindow();
        app.Run(window);
    }
}

ファイル名:AssemblyInfo.cs


using System.Windows;

[assembly:ThemeInfo(
    ResourceDictionaryLocation.None,            //where theme specific resource dictionaries are located
                                                //(used if a resource is not found in the page,
                                                // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly   //where the generic resource dictionary is located
                                                //(used if a resource is not found in the page,
                                                // app, or any theme specific resource dictionaries)
)]

ファイル名:MainWindow.xaml.cs


using System.IO;
using System.Windows;
using ImageMagick;

namespace ScreenshotWatcher01;

public partial class MainWindow : Window
{
    private FileSystemWatcher? _watcher;

    public MainWindow()
    {
        Title = "スクリーンショット監視";
        Width = 300;
        Height = 150;
        
        WatchScreenshotFolder();
    }

    private void WatchScreenshotFolder()
    {
        string screenshotFolder = System.IO.Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
            "Screenshots");

        if (!Directory.Exists(screenshotFolder))
        {
            MessageBox.Show("スクリーンショットフォルダが見つかりません");
            return;
        }

        _watcher = new FileSystemWatcher(screenshotFolder, "*.png")
        {
            NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime,
            EnableRaisingEvents = true
        };

        _watcher.Created += async (s, e) =>
        {
            await Task.Delay(500); // 書き込み完了まで待つ
            try
            {
                await Dispatcher.InvokeAsync(() =>
                {
                    ProcessImage(e.FullPath);
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"エラー: {ex.Message}");
            }
        };
    }

    private void ProcessImage(string path)
    {
        using var image = new MagickImage(path);

        // 減色:256色
        image.Quantize(new QuantizeSettings { Colors = 256 });
        image.Format = MagickFormat.Png8;

        // Base64へ変換
        using var ms = new MemoryStream();
        image.Write(ms);
        string base64 = Convert.ToBase64String(ms.ToArray());

        Clipboard.SetText($"<img src=\"data:image/png;base64,{base64}\" alt=\"image\" />");
        MessageBox.Show("画像を256色に減色し、Base64としてクリップボードにコピーしました。", "完了");
    }

    protected override void OnClosed(EventArgs e)
    {
        _watcher?.Dispose();
        base.OnClosed(e);
    }
}

コメント