Skip to content
Hokusai2.2.2
ivantokar.com

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 transparency
try 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"))
  • A circular crop of the landscape centred on the lighthouse, with transparent corners.
    avatar.pngPNG · 256 × 256 · 64 KB
  • The same circular avatar as a WebP with transparency.
    avatar.webpWEBP · 256 × 256 · 7 KB
  • The circular avatar on a paper-coloured square, as a JPEG.
    avatar.jpg (flat)JPEG · 256 × 256 · 16 KB
  1. resize(width: 256, height: 256, fit: .cover, position: .attention) makes the square and keeps the interesting part in it.
  2. 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.
  3. 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).
  4. PNG or WebP keep the transparency; for places that cannot show alpha, flatten(background:) onto the page colour and encode JPEG (why flatten last).
  • 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 before withAlpha feathers the edge.
  • Retina: build at 512 and let the page scale it down.