Created
April 19, 2024 14:58
-
-
Save pardeike/248e88ffe469e896e109a52e73ff86de to your computer and use it in GitHub Desktop.
Expanding an image with a brush
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Author
pardeike
commented
Apr 19, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment