User:Habst/getKbr.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// nodejs script to get kbr.de newspaper scans
import { writeFile } from 'node:fs/promises'
import { Readable } from 'node:stream'
import sharp from 'sharp';
import fs from 'fs';

const prefix = 'https://viewerd.kbr.be/display/N/JB735/1925/03/04/01/zoomtiles/KB_JB735_1925-03-04_01-00004/';
const page = '3';
const imageWidth = 768;
const imageHeight = 768;
const gridCols = 7; // 6 + 1
const gridRows = 9; // 8 + 1

for (let col = 0; col < gridCols; col++) {
  for (let row = 0; row < gridRows; row++) {
    const fname = `${page}-${col}-${row}.jpg`;
    if (fs.existsSync(`data/${fname}`)) continue;
    const url = prefix + fname;
    console.log(url);
    const r = await fetch(url);
    const body = Readable.fromWeb(r.body);
    await writeFile(`data/${fname}`, body);
  }
}

const finalWidth = gridCols * imageWidth;
const finalHeight = gridRows * imageHeight;

function prepareImages() {
  const images = [];
  for (let row = 0; row < gridRows; row++) {
    for (let col = 0; col < gridCols; col++) {
      const filename = `data/${page}-${col}-${row}.jpg`;
      images.push({
        input: filename,
        top: row * imageHeight,
        left: col * imageWidth,
      });
    }
  }
  console.group(images.length);
  return images;
}
sharp({
  create: {
    width: finalWidth,
    height: finalHeight,
    channels: 4, // RGBA
    background: { r: 0, g: 0, b: 0, alpha: 0 },
  }
})
.composite(prepareImages())
.toFile('result.jpg', (err, info) => {
  if (err) throw err;
  console.log('Image saved:', info);
});