Circular avatar
Goal. From any photo, make a 256 × 256 circular avatar. Inputs: scene.png, emblem.png (its alpha channel is the circle). Needs: Hokusai 2.2.2.
let size = 256// A circular mask: the alpha channel of the emblem is a disc with soft edges.let mask = try Hokusai(url: URL(fileURLWithPath: "emblem.png")).resize(width: size).extractChannel(.alpha)
let avatar = try Hokusai(url: URL(fileURLWithPath: "scene.png")) .resize(width: size, height: size, fit: .cover, position: .attention) .withAlpha(from: mask)
try await avatar.png().write(to: URL(fileURLWithPath: "avatar.png")) // keeps transparencytry await avatar.webp(quality: 85).write(to: URL(fileURLWithPath: "avatar.webp"))// Variation: for places without alpha, flatten onto the page colour and use JPEG.try await avatar.flatten(background: Color(red: 0.97, green: 0.95, blue: 0.9)).jpeg(quality: 90) .write(to: URL(fileURLWithPath: "avatar.jpg"))
avatar.pngPNG · 256 × 256 · 64 KB 
avatar.webpWEBP · 256 × 256 · 7 KB 
avatar.jpg (flat)JPEG · 256 × 256 · 16 KB
How it works
Section titled “How it works”resize(width: 256, height: 256, fit: .cover, position: .attention)makes the square and keeps the interesting part in it.- A circular mask is the alpha channel of an existing round image, resized to 256 px:
extractChannel(.alpha)turns it into a grey image, white inside the disc and black outside. withAlpha(from: mask)uses that luminance as the avatar’s alpha: white keeps pixels, black hides them. The mask must come out the same size as the avatar, which is why both are 256 px (channels).- PNG or WebP keep the transparency; for places that cannot show alpha,
flatten(background:)onto the page colour and encode JPEG (why flatten last).
Variations
Section titled “Variations”- A different shape: any image with an alpha channel or a grey image of the right size works as the mask (a rounded square, a hexagon).
- A soft edge:
blur(sigma: 2)on the mask beforewithAlphafeathers the edge. - Retina: build at 512 and let the page scale it down.