똑같은 삽질은 2번 하지 말자

AWS Lambda를 이용한 Image Resizing 본문

카테고리 없음

AWS Lambda를 이용한 Image Resizing

곽빵 2022. 3. 11. 21:22

개요

AWS Lambda를 이용해 Image Resizing 해보기

해보고자 하는 기능은 S3 버킷에 이미지가 추가될 때 적절한 사이즈로 리사이징을 하는 함수를 만들것이다.

 

1. Lambda 함수를 생성한다.

 

2. Trigger 추가

트리거를 추가해 주고 S3 버킷에 이미지를 넣어보는데 

event.Records[0].s3 안에 object에 넣은 이미지의 아이디가 들어있었다.

그럼 그 아이디를 이용해 버킷의 이미지를 가져와서 리사이징해서 다른 디렉터리에 넣어놓으면 된다.

 

3. 람다함수 작성

새로운 람다함수용 디렉터리를 생성해서 작성해준다.

람다함수는 개발환경을 마련하는게 좀 애매해서 일단 vscode에서 작성해 실제로 업로드해서 테스트하는 방식으로 하자.

npm install --arch=x64 --platform=linux sharp

sharp를 설치하는데 aws Lambda에 호환되는 리눅스용으로 깔아준다.

 

index.js

const sharp = require("sharp");
const aws = require("aws-sdk");
const s3 = new aws.S3();

const transformationOptions = [
  { name: "w140", width: 140 },
  { name: "w600", width: 600 },
];

exports.handler = async (event) => {
  try {
    const Key = event.Records[0].s3.object.key;
    const keyOnly = Key.split("/")[1];
    console.log(`Image Resizing: ${keyOnly}`);
    const image = await s3
      .getObject({ Bucket: "first-image-storage", Key })
      .promise();
    console.log("Get Image Success", image);
    await Promise.all(
      transformationOptions.map(async ({ name, width }) => {
        try {
          const newKey = `${name}/${keyOnly}`;
          console.log("newKey", newKey);

          const resizedImage = await sharp(image.Body)
            .rotate()
            .resize(width)
            .toBuffer();
          await s3
            .putObject({
              Bucket: "first-image-storage",
              Body: resizedImage,
              Key: newKey,
            })
            .promise();
        } catch (err) {
          throw err;
        }
      })
    );
    return {
      statusCode: 200,
      body: event,
    };
  } catch (err) {
    console.log("!!!!!!!!!!!!Error: ", err);
    return {
      statusCode: 500,
      body: event,
    };
  }
};
  • width-140와 width-600으로 두개의 패턴으로 작성
  • index.js안에 exports.handler는 무조건 있어야한다.
  • aws-sdk는 설치안해도? 되는거 같다.
  • .promise()로 해야 Promise로 리턴된다.

4. 작성한 람다함수 업로드

(node_modules포함)압축해서 압축한 파일 그대로 업로드하면 된다.

 

5. 권한설정

람다함수가 s3 버킷에 쓰기권한을 가져야 리사이징한 이미지를 넣을 수 있기 때문에 권한설정이 필요하다.

 

 

Comments