dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

Typescript で sharp による画像の各ピクセルの色を変更

2023-01-08 14:07:21 | Node.js
Typescript で画像処理モジュールの sharp を使って、画像の各ピクセルの色を変更する方法のメモ。

■インストール
npm install sharp
npm i --save @types/sharp


■プログラム
.raw().toBuffer() で画像の各ピクセルのデータを参照できるようにした後で、各ピクセルの色を補色に変更し、変更後のデータで画像を生成してファイルに保存しています。
import * as fs from 'fs';
import sharp from 'sharp';

function change_color(data: any) {
  const size = data.length;

  for (let idx = 0; idx < size; idx += 4) {
    let r = data[idx];
    let g = data[idx+1];
    let b = data[idx+2];

    // 補色に変更
    let max_min = Math.max(r, g, b) + Math.min(r, g, b);
    data[idx] = max_min - r;
    data[idx+1] = max_min - g;
    data[idx+2] = max_min - b;
  }
}

(async () => {
  const img_in_path: string = 'test1.png';
  const img_out_path: string = 'conv1.png';

  const img =
    await await sharp(img_in_path)
      .raw()
      .toBuffer({resolveWithObject: true});

  change_color(img.data);

  await sharp(new Uint8ClampedArray(img.data.buffer),
              {raw: {width: img.info.width,
                     height: img.info.height,
                     channels: img.info.channels}})
    .toFile(img_out_path);
})();


この記事についてブログを書く
« MySQL の Connection Pool | トップ | Android Studio のエディタで... »

Node.js」カテゴリの最新記事