Node sharpNodejs sharp exampleNext.js sharpReact sharpsharp 라이브러리

이미지 최적화 라이브러리 Sharp 가이드

KUKJIN LEE
KUKJIN LEE
2024년 11월 7일
256

Sharp란 무엇인가요?

sharp는 고성능 이미지 처리 라이브러리로, 이미지 크기 조정, 포맷 변환, 압축 등 다양한 작업을 효율적으로 수행할 수 있습니다. Node.js 환경에서 이미지 처리를 손쉽게 할 수 있어 웹 애플리케이션의 성능 향상에 도움이 됩니다.

 

설치

npm i sharp
 

Sharp 사용 예제

설치가 완료되면 sharp를 사용하여 이미지를 쉽게 처리할 수 있습니다.

const sharp = require('sharp');

sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg', (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log(info);
    }
  });

input.jpg 이미지를 300x200 크기로 리사이즈하고, output.jpg로 저장합니다. sharp는 매우 직관적이고 사용하기 쉬운 API를 제공하기 때문에, 이미지 처리 작업을 간편하게 구현할 수 있습니다.

 

자주 사용하는 기능

1. 이미지 포맷 변환

이미지 파일을 다른 포맷으로 변환하는 것도 가능합니다.

sharp('input.png')
  .jpeg()
  .toFile('output.jpg', (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log(info);
    }
  });

 

2. 이미지 품질 조정

JPEG나 PNG 이미지의 품질을 조정할 수 있습니다.

sharp('input.jpg')
  .jpeg({ quality: 80 })
  .toFile('output.jpg', (err, info) => {
    if (err) {
      console.error(err);
    } else {
      console.log(info);
    }
  });

 

S3에 이미지 업로드하기 위해 Sharp 사용하기

사용법도 중요하지만 우리에게 가장 중요한 건 실제 구현이 아닐까 생각됩니다. Amazon S3에 업로드하는 예제 코드입니다.

const AWS = require('aws-sdk');
const sharp = require('sharp');
const fs = require('fs');

// AWS S3 설정
const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION,
});

// 이미지 처리 및 업로드 함수
const uploadToS3 = async (inputPath, bucketName, key) => {
  try {
    // 이미지를 리사이즈
    const buffer = await sharp(inputPath).resize(300, 200).toBuffer();

    // S3에 업로드
    const params = {
      Bucket: bucketName,
      Key: key,
      Body: buffer,
      ContentType: 'image/jpeg',
    };

    const result = await s3.upload(params).promise();
    console.log('File uploaded successfully:', result.Location);
  } catch (err) {
    console.error('Error uploading file:', err);
  }
};
#Node sharp#Nodejs sharp example#Next.js sharp#React sharp#sharp 라이브러리#이미지 최적화#이미지 리사이징#이미지 리사이즈#npm