[NestJS] pngjs로 image 생성해서 응답하기

bluejoy·2023년 3월 16일
0

NestJS

목록 보기
1/1

개요

간단한 테스트 서버를 만들어서 이미지를 보내려 했는데, 다양한 색의 이미지를 어디 저장해서 가져오기도 그래서 실시간으로 생성해서 뿌려주기로 했다.
이미지의 사이즈가 200*200이므로 초당 1000개 정도는 문제가 없을 듯 한데, 테스트를 해보니 이미지 하나 생성에 20ms가 걸렸다. 50장은 괜찮을 듯.

코드

import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
import { PNG } from 'pngjs';

@Controller('photos')
export class PhotosController {
  @Get('gen')
  test(@Res() res: Response) {
    const width = 200;
    const height = 200;
    const image = new PNG({
      width: width,
      height: height,
    });
    for (let y = 0; y < height; y++) {
      for (let x = 0; x < width; x++) {
        const idx = (width * y + x) * 4;
        image.data[idx] = 10; // R
        image.data[idx + 1] = 0; // G
        image.data[idx + 2] = 255; // B
        image.data[idx + 3] = 255; // A
      }
    }
    const buffer = PNG.sync.write(image);
    res.type('image/png');
    res.send(buffer);
  }
}
profile
개발자 지망생입니다.

0개의 댓글