| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- const { fromFile } = require('geotiff')
- const sharp = require('sharp')
- const fs = require('fs')
- const path = require('path')
- async function main() {
- const tiffPath = path.resolve(__dirname, '../de99928f1689454084d1af33ec3cc155.tif')
- const outPath = path.resolve(__dirname, '../public/de99928f-preview.png')
- if (!fs.existsSync(tiffPath)) {
- console.error('TIFF not found:', tiffPath)
- process.exit(1)
- }
- console.log('Reading TIFF...')
- const tiff = await fromFile(tiffPath)
- const image = await tiff.getImage()
- const w = image.getWidth()
- const h = image.getHeight()
- console.log('TIFF size:', w, 'x', h)
- // 控制生成纹理尺寸:原图 14997x19876 太大,浏览器加载 123MB PNG 容易失败。
- // 4096 宽按原比例缩放后约 5425 高,文件体积降到 1/4 左右,仍然足够清晰。
- const targetW = 4096
- const targetH = Math.round(targetW * h / w)
- console.log('Target size:', targetW, 'x', targetH)
- console.log('Reading rasters at target size...')
- const data = await image.readRasters({ width: targetW, height: targetH, samples: [0, 1, 2] })
- const r = data[0]
- const g = data[1]
- const b = data[2]
- console.log('Building RGBA with alpha mask...')
- const rgba = Buffer.alloc(targetW * targetH * 4)
- let blackCount = 0
- for (let i = 0; i < targetW * targetH; i++) {
- const isBlack = r[i] < 10 && g[i] < 10 && b[i] < 10
- rgba[i * 4] = r[i]
- rgba[i * 4 + 1] = g[i]
- rgba[i * 4 + 2] = b[i]
- rgba[i * 4 + 3] = isBlack ? 0 : 255
- if (isBlack) blackCount++
- }
- console.log('Black pixels masked:', blackCount)
- await sharp(rgba, { raw: { width: targetW, height: targetH, channels: 4 } })
- .png({ compressionLevel: 9, adaptiveFiltering: true })
- .toFile(outPath)
- console.log('Saved:', outPath)
- }
- main().catch(e => {
- console.error(e)
- process.exit(1)
- })
|