| 100 | |
| 101 | // 给图片添加圆角并添加 padding |
| 102 | const createIcon = async (inputPath, tempOutputPath, icnsOutputPath) => { |
| 103 | sharp(inputPath) |
| 104 | .resize({ |
| 105 | // 确保图片尺寸一致 |
| 106 | width: 1024, |
| 107 | height: 1024, |
| 108 | fit: 'contain', |
| 109 | background: { r: 0, g: 0, b: 0, alpha: 0 }, |
| 110 | }) |
| 111 | .composite([ |
| 112 | // rx ry是圆角半径 |
| 113 | { |
| 114 | input: Buffer.from( |
| 115 | `<svg> |
| 116 | <rect x="0" y="0" width="1024" height="1024" rx="250" ry="250" /> |
| 117 | </svg>` |
| 118 | ), |
| 119 | blend: 'dest-in', |
| 120 | }, |
| 121 | ]) |
| 122 | // top/bottom/left/right 是 padding |
| 123 | .extend({ |
| 124 | top: 120, |
| 125 | bottom: 120, |
| 126 | left: 120, |
| 127 | right: 120, |
| 128 | background: { r: 0, g: 0, b: 0, alpha: 0 }, |
| 129 | }) |
| 130 | .toFile(tempOutputPath) |
| 131 | .then(() => { |
| 132 | console.log( |
| 133 | 'Image processing complete with rounded corners and padding.' |
| 134 | ) |
| 135 | |
| 136 | // 读取处理后的 PNG 文件 |
| 137 | fs.readFile(tempOutputPath, (err, data) => { |
| 138 | if (err) { |
| 139 | console.error('Error reading processed PNG file:', err) |
| 140 | return |
| 141 | } |
| 142 | |
| 143 | // 转换 PNG 到 ICNS 格式 |
| 144 | const icnsBuffer = png2icons.createICNS(data, 1, 0) |
| 145 | if (icnsBuffer) { |
| 146 | fs.writeFile(icnsOutputPath, icnsBuffer, (writeErr) => { |
| 147 | if (writeErr) { |
| 148 | console.error('Error writing ICNS file:', writeErr) |
| 149 | } else { |
| 150 | console.log( |
| 151 | 'ICNS file created successfully:', |
| 152 | icnsOutputPath |
| 153 | ) |
| 154 | // 删除临时文件 |
| 155 | fs.remove(tempOutputPath) |
| 156 | } |
| 157 | }) |
| 158 | } else { |
| 159 | console.error('Failed to convert PNG to ICNS.') |