Skip to content

이미지 처리 API

Sharp는 크기 조정, 자르기, 회전, 필터 등 풍부한 이미지 처리 기능을 제공합니다.

크기 조정 (resize)

기본 사용법

javascript
import sharp from 'sharp';

// 지정된 크기로 조정
sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg');

// 너비만 지정, 높이 자동 계산
sharp('input.jpg')
  .resize(300)
  .toFile('output.jpg');

// 높이만 지정, 너비 자동 계산
sharp('input.jpg')
  .resize(null, 200)
  .toFile('output.jpg');

크기 조정 옵션

javascript
sharp('input.jpg')
  .resize(300, 200, {
    // 크기 조정 알고리즘
    kernel: sharp.kernel.lanczos3,
    
    // 위치
    position: 'center',
    
    // 배경색
    background: { r: 255, g: 255, b: 255, alpha: 1 },
    
    // 종횡비 유지 여부
    fit: 'cover',
    
    // 확대하지 않음
    withoutEnlargement: true,
    
    // 축소하지 않음
    withoutReduction: false
  })
  .toFile('output.jpg');

크기 조정 알고리즘

javascript
// 사용 가능한 크기 조정 알고리즘
sharp.kernel.nearest      // 최근접 이웃
sharp.kernel.cubic        // 3차 보간
sharp.kernel.mitchell     // Mitchell-Netravali
sharp.kernel.lanczos2     // Lanczos 2-lobed
sharp.kernel.lanczos3     // Lanczos 3-lobed (기본값)

적합 모드

javascript
// cover: 종횡비 유지, 초과 부분 자르기
sharp('input.jpg').resize(300, 200, { fit: 'cover' })

// contain: 종횡비 유지, 배경 추가
sharp('input.jpg').resize(300, 200, { fit: 'contain' })

// fill: 지정된 크기로 늘리기
sharp('input.jpg').resize(300, 200, { fit: 'fill' })

// inside: 종횡비 유지, 원본 크기 초과하지 않음
sharp('input.jpg').resize(300, 200, { fit: 'inside' })

// outside: 종횡비 유지, 최소 지정 크기 달성
sharp('input.jpg').resize(300, 200, { fit: 'outside' })

자르기 (extract)

javascript
// 지정된 영역 자르기
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 300, height: 200 })
  .toFile('output.jpg');

// 자르기 및 크기 조정
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 300, height: 200 })
  .resize(150, 100)
  .toFile('output.jpg');

회전 (rotate)

javascript
// 90도 회전
sharp('input.jpg')
  .rotate(90)
  .toFile('output.jpg');

// 회전 및 배경색 지정
sharp('input.jpg')
  .rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
  .toFile('output.jpg');

뒤집기 (flip/flop)

javascript
// 수직 뒤집기
sharp('input.jpg')
  .flip()
  .toFile('output.jpg');

// 수평 뒤집기
sharp('input.jpg')
  .flop()
  .toFile('output.jpg');

블러 (blur)

javascript
// 가우시안 블러
sharp('input.jpg')
  .blur(5)
  .toFile('output.jpg');

// 선명화
sharp('input.jpg')
  .sharpen()
  .toFile('output.jpg');

// 사용자 정의 선명화 매개변수
sharp('input.jpg')
  .sharpen({
    sigma: 1,
    flat: 1,
    jagged: 2
  })
  .toFile('output.jpg');

필터 (filters)

그레이스케일

javascript
sharp('input.jpg')
  .grayscale()
  .toFile('output.jpg');

반전

javascript
sharp('input.jpg')
  .negate()
  .toFile('output.jpg');

감마 보정

javascript
sharp('input.jpg')
  .gamma(2.2)
  .toFile('output.jpg');

밝기/대비

javascript
sharp('input.jpg')
  .modulate({
    brightness: 1.2,    // 밝기 (0.1-2.0)
    saturation: 0.8,    // 채도 (0-2.0)
    hue: 180            // 색조 (0-360)
  })
  .toFile('output.jpg');

색상 작업

색조 분리

javascript
sharp('input.jpg')
  .tint({ r: 255, g: 0, b: 0 })
  .toFile('output.jpg');

색상 행렬

javascript
sharp('input.jpg')
  .recomb([
    [0.3588, 0.7044, 0.1368],
    [0.2990, 0.5870, 0.1140],
    [0.0000, 0.0000, 1.0000]
  ])
  .toFile('output.jpg');

채널 작업

채널 분리

javascript
// 빨간색 채널 가져오기
sharp('input.jpg')
  .extractChannel('red')
  .toFile('red-channel.jpg');

// 모든 채널 가져오기
const channels = await sharp('input.jpg').separate();

채널 병합

javascript
// 별도의 채널 파일에서 병합
sharp('red.jpg')
  .joinChannel(['green.jpg', 'blue.jpg'])
  .toFile('merged.jpg');

조합 작업

javascript
// 체인 작업
sharp('input.jpg')
  .resize(800, 600)
  .rotate(90)
  .blur(2)
  .sharpen()
  .jpeg({ quality: 80 })
  .toFile('output.jpg');

성능 최적화

스트림 처리

javascript
const fs = require('fs');

fs.createReadStream('input.jpg')
  .pipe(sharp().resize(300, 200))
  .pipe(fs.createWriteStream('output.jpg'));

일괄 처리

javascript
const sharp = require('sharp');
const fs = require('fs').promises;

async function processImages() {
  const files = await fs.readdir('./images');
  
  const promises = files
    .filter(file => file.endsWith('.jpg'))
    .map(async file => {
      await sharp(`./images/${file}`)
        .resize(300, 200)
        .jpeg({ quality: 80 })
        .toFile(`./output/${file}`);
    });
    
  await Promise.all(promises);
}

오류 처리

javascript
try {
  await sharp('input.jpg')
    .resize(300, 200)
    .toFile('output.jpg');
} catch (error) {
  console.error('이미지 처리 실패:', error.message);
}

관련 링크

Apache 2.0 라이선스에 따라 릴리스되었습니다.