以下の内容はhttps://rksoftware.hatenablog.com/entry/2025/02/16/120000より取得しました。


画像に枠線を付けるコード

画像には枠線を付けたい派です。

■ 例えば


こういう画像。画面キャプチャ画像などでよくありますね。背景色は枠いっぱいまでの画像。

これを同じ背景色のページに貼ると、なんということでしょう!

画像が埋もれてしまいます。特に Web ページに乗せる画像だと、ユーザーが背景色を変えているカモなど、考えると朝も起きられません。

■ そこで今回の C# コードです

.NET なら簡単なコードで枠線を付けられます。

例えばこんな感じに。

この画像を同じ背景のページに乗せると

いいでしょ。

■ コード

見てください、この雑なコード!
自分で使うプログラムなど、こういうのでいいんですよこういうので。

var name = args.FirstOrDefault() ?? string.Empty;
if (string.IsNullOrWhiteSpace(name)) return;

if (System.IO.Directory.Exists(name))
    foreach (var file in System.IO.Directory.GetFiles(name))
        B(file);

if (System.IO.File.Exists(name))
    B(name);

static void B(string name)
{
    var extension = System.IO.Path.GetExtension(name);
    if (!new[] { ".jpg", ".bmp", ".png" }.Contains(extension)) return;

    var nameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(name);
    var directoryName = System.IO.Path.GetDirectoryName(name);
    var fileName = System.IO.Path.Combine(directoryName, $"_2_{nameWithoutExtension}{extension}");
    if (System.IO.File.Exists(fileName)) return;

    using var img = System.Drawing.Image.FromFile(name);
    using var bmp = new System.Drawing.Bitmap(img.Width + 2, img.Height + 2);
    bmp.SetResolution(bmp.Width, bmp.Height);
    ;
    using var g = System.Drawing.Graphics.FromImage(bmp);
    g.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(255, 127, 127, 127)), 0, 0, bmp.Width, bmp.Height);
    g.DrawImage(img, 1, 1, img.Width, img.Height);

    bmp.Save(fileName);
}

github.com

www.nuget.org

■ 使い方

> ImageBorderConsole <image file name>



以上の内容はhttps://rksoftware.hatenablog.com/entry/2025/02/16/120000より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14