Add-Type -AssemblyName System.Drawing

$srcPath = "E:\wk-lab\u-desk\build\windows\app-icon.png"
$icoPath = "E:\wk-lab\u-desk\build\windows\icon.ico"
$sizes = @(256, 128, 64, 48, 32, 16)

$src = [System.Drawing.Image]::FromFile($srcPath)
$fs = New-Object System.IO.FileStream($icoPath, [System.IO.FileMode]::Create)
$w = New-Object System.IO.BinaryWriter($fs)

$w.Write([uint16]0)
$w.Write([uint16]1)
$w.Write([uint16]$sizes.Count)

foreach ($sz in $sizes) {
    $bmp = New-Object System.Drawing.Bitmap($sz, $sz, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
    $g = [System.Drawing.Graphics]::FromImage($bmp)
    $g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
    $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
    $g.DrawImage($src, 0, 0, $sz, $sz)
    $g.Dispose()

    $ms = New-Object System.IO.MemoryStream
    $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
    $bytes = $ms.ToArray()
    $ms.Dispose()
    $bmp.Dispose()

    $w.Write([uint32]40)
    $w.Write([int32]$sz)
    $w.Write([int32]$sz)
    $w.Write([uint16]1)
    $w.Write([uint32]32)
    $w.Write([uint32]$bytes.Length)
    $w.Write([uint32]22)
    $w.Write($bytes)
}

$w.Close()
$fs.Close()
$src.Dispose()

$item = Get-Item $icoPath
Write-Output "ICO: $($item.Name) ($([math]::Round($item.Length / 1KB)) KB)"
