💾 Archived View for iich.space › src › util › images.ts captured on 2022-03-01 at 15:52:29.

View Raw

More Information

⬅️ Previous capture (2021-12-03)

-=-=-=-=-=-=-

import { exec as execAsync } from 'child_process';
import { createHash } from 'crypto';
import { mkdtemp, rename, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { promisify } from 'util';

import { File } from '@/gemini/request';

const exec = promisify(execAsync);

const getSha = (buffer: Buffer) => {
  const hash = createHash('sha256');
  hash.update(buffer);
  return hash.digest('hex').slice(0, 32);
};

export const processImageUpload = async (file: File): Promise<string> => {
  const validMimeTypes = ['image/png', 'image/jpeg'];

  if (file.data.length === 0) {
    throw new Error('missing file upload');
  }

  if (validMimeTypes.includes(file.mime) === false) {
    throw new Error('invalid image type');
  }

  const dir = await mkdtemp(join(tmpdir(), 'iich-'));
  const sha = getSha(file.data);

  const sourcePath = join(dir, `${sha}`);
  const convertPath = join('.', 'images', `${sha}.png`);
  const targetPath = join('.', 'images', `${sha}.png`);

  await writeFile(sourcePath, file.data);

  await exec(
    `convert ${sourcePath} -resize '512x512>' -ordered-dither o2x2,3 ${convertPath}`,
  );

  await rename(convertPath, targetPath);

  return sha;
};