1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Next JSで画像を返すAPIを作る

Posted at

Next JSで画像生成APIを作る時、調べてもなかなか出なかったので、ここに残しておきます

npm i canvas

canvasのライブラリをインストールする

image.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import { createCanvas } from 'canvas';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<any>
) {
    const canvas = createCanvas(1920, 1080); //1920×1080の画像を作成
    const ctx = canvas.getContext('2d'); //コンテキストを取得

    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Content-Disposition', 'inline;');
    res.status(200).write(canvas.toBuffer()); //バッファーを返す
    res.end();
}

これで、apiにアクセスすると、1920×1080の透過画像が返って来るようになり、ctxで色々加工をするとそれも反映されます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?