Skip to content

Instantly share code, notes, and snippets.

@pardeike
Created April 19, 2024 14:58
Show Gist options
  • Select an option

  • Save pardeike/248e88ffe469e896e109a52e73ff86de to your computer and use it in GitHub Desktop.

Select an option

Save pardeike/248e88ffe469e896e109a52e73ff86de to your computer and use it in GitHub Desktop.

Revisions

  1. pardeike created this gist Apr 19, 2024.
    56 changes: 56 additions & 0 deletions Dilute.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Processing;
    using SixLabors.ImageSharp.PixelFormats;
    using Image = SixLabors.ImageSharp.Image;
    using SixLabors.ImageSharp.Formats.Png;

    class Program
    {
    static readonly PngEncoder encoder = new()
    {
    ColorType = PngColorType.RgbWithAlpha,
    TransparentColorMode = PngTransparentColorMode.Preserve,
    BitDepth = PngBitDepth.Bit8,
    CompressionLevel = PngCompressionLevel.BestSpeed
    };

    static void Main()
    {
    using var original = Image.Load<Rgba32>("star.png"); // original
    using var circle = Image.Load<Rgba32>("circle.png"); // a circle brush with uneven size (9x9 i.e.)
    ApplyDilation(original, circle).SaveAsPng("star_expanded.png", encoder);
    }

    static Image<Rgba32> ApplyDilation(Image<Rgba32> image, Image<Rgba32> circle)
    {
    var expansion = circle.Width / 2;
    var newImage = image.Clone();
    var width = newImage.Width;
    var height = newImage.Height;

    newImage.Mutate(ctx =>
    {
    for (var y = 0; y < height; y++)
    for (var x = 0; x < width; x++)
    newImage[x, y] = new Rgba32(255, 255, 255, 0);

    for (var y = expansion; y < height - expansion; y++)
    for (var x = expansion; x < width - expansion; x++)
    {
    var baseA = image[x, y].A;
    if (baseA < 64)
    continue;

    for (var dy = y - expansion; dy <= y + expansion; dy++)
    for (var dx = x - expansion; dx <= x + expansion; dx++)
    {
    byte a = (byte)(baseA * circle[dx - x + expansion, dy - y + expansion].A / 255);
    if (a > newImage[dx, dy].A)
    newImage[dx, dy] = new Rgba32(255, 255, 255, a);
    }
    }
    });

    return newImage;
    }
    }