고급 예제
여기에는 복잡한 이미지 처리 작업을 포함한 Sharp의 고급 사용 예제가 제공됩니다.
이미지 합성
워터마크 추가
javascript
import sharp from 'sharp';
// 텍스트 워터마크 추가
await sharp('input.jpg')
.composite([
{
input: Buffer.from(`
<svg width="200" height="100">
<text x="10" y="50" font-family="Arial" font-size="24" fill="white">
Watermark
</text>
</svg>
`),
top: 10,
left: 10
}
])
.jpeg()
.toFile('output.jpg');이미지 오버레이
javascript
// 여러 이미지 오버레이
await sharp('background.jpg')
.composite([
{
input: 'overlay1.png',
top: 100,
left: 100
},
{
input: 'overlay2.png',
top: 200,
left: 200
}
])
.jpeg()
.toFile('output.jpg');채널 작업
채널 분리
javascript
// RGB 채널 분리
const channels = await sharp('input.jpg').separate();
// 각 채널 저장
await sharp(channels[0]).toFile('red-channel.jpg');
await sharp(channels[1]).toFile('green-channel.jpg');
await sharp(channels[2]).toFile('blue-channel.jpg');채널 병합
javascript
// 별도의 채널 파일에서 병합
await sharp('red-channel.jpg')
.joinChannel(['green-channel.jpg', 'blue-channel.jpg'])
.toFile('merged.jpg');색상 공간 변환
RGB를 CMYK로 변환
javascript
await sharp('input.jpg')
.toColourspace(sharp.colourspace.cmyk)
.tiff()
.toFile('output.tiff');Lab 색상 공간으로 변환
javascript
await sharp('input.jpg')
.toColourspace(sharp.colourspace.lab)
.tiff()
.toFile('output.tiff');고급 필터
사용자 정의 선명화
javascript
await sharp('input.jpg')
.sharpen({
sigma: 1,
flat: 1,
jagged: 2
})
.toFile('output.jpg');감마 보정
javascript
await sharp('input.jpg')
.gamma(2.2)
.toFile('output.jpg');색조 분리
javascript
await sharp('input.jpg')
.tint({ r: 255, g: 0, b: 0 })
.toFile('output.jpg');다중 페이지 이미지 처리
TIFF 다중 페이지 처리
javascript
// 모든 페이지 처리
await sharp('multi-page.tiff', { pages: -1 })
.resize(800, 600)
.tiff()
.toFile('output.tiff');
// 특정 페이지 처리
await sharp('multi-page.tiff', { pages: 0 })
.resize(800, 600)
.jpeg()
.toFile('page0.jpg');PDF 처리
javascript
// PDF 첫 페이지 처리
await sharp('document.pdf', { pages: 0 })
.resize(800, 600)
.jpeg()
.toFile('page0.jpg');반응형 이미지 생성
여러 크기 생성
javascript
async function generateResponsiveImages(inputPath) {
const sizes = [
{ width: 320, height: 240, suffix: 'small' },
{ width: 640, height: 480, suffix: 'medium' },
{ width: 1280, height: 960, suffix: 'large' },
{ width: 1920, height: 1440, suffix: 'xlarge' }
];
const promises = sizes.map(async ({ width, height, suffix }) => {
await sharp(inputPath)
.resize(width, height, { fit: 'cover' })
.jpeg({ quality: 80 })
.toFile(`output-${suffix}.jpg`);
});
await Promise.all(promises);
}여러 형식 생성
javascript
async function generateMultipleFormats(inputPath) {
const formats = [
{ format: 'jpeg', quality: 80, ext: 'jpg' },
{ format: 'webp', quality: 80, ext: 'webp' },
{ format: 'avif', quality: 80, ext: 'avif' }
];
const promises = formats.map(async ({ format, quality, ext }) => {
const image = sharp(inputPath).resize(800, 600);
switch (format) {
case 'jpeg':
await image.jpeg({ quality }).toFile(`output.${ext}`);
break;
case 'webp':
await image.webp({ quality }).toFile(`output.${ext}`);
break;
case 'avif':
await image.avif({ quality }).toFile(`output.${ext}`);
break;
}
});
await Promise.all(promises);
}이미지 분석
이미지 통계 정보 가져오기
javascript
async function analyzeImage(filePath) {
const metadata = await sharp(filePath).metadata();
const stats = await sharp(filePath).stats();
return {
metadata,
stats: {
isOpaque: stats.isOpaque,
dominant: stats.dominant,
channels: stats.channels
}
};
}이미지 유형 감지
javascript
async function detectImageType(filePath) {
const metadata = await sharp(filePath).metadata();
return {
format: metadata.format,
hasAlpha: metadata.hasAlpha,
isOpaque: metadata.isOpaque,
channels: metadata.channels,
colorSpace: metadata.space
};
}고급 자르기
스마트 자르기
javascript
async function smartCrop(inputPath, outputPath, width, height) {
// 이미지 정보 가져오기
const metadata = await sharp(inputPath).metadata();
// 자르기 영역 계산
const aspectRatio = width / height;
const imageAspectRatio = metadata.width / metadata.height;
let cropWidth, cropHeight, left, top;
if (aspectRatio > imageAspectRatio) {
// 대상이 더 넓음, 높이 기준
cropHeight = metadata.height;
cropWidth = cropHeight * aspectRatio;
top = 0;
left = (metadata.width - cropWidth) / 2;
} else {
// 대상이 더 높음, 너비 기준
cropWidth = metadata.width;
cropHeight = cropWidth / aspectRatio;
left = 0;
top = (metadata.height - cropHeight) / 2;
}
await sharp(inputPath)
.extract({ left: Math.round(left), top: Math.round(top), width: Math.round(cropWidth), height: Math.round(cropHeight) })
.resize(width, height)
.toFile(outputPath);
}이미지 최적화
자동 최적화
javascript
async function autoOptimize(inputPath, outputPath) {
const metadata = await sharp(inputPath).metadata();
let image = sharp(inputPath);
// 이미지 유형에 따라 최적 형식 선택
if (metadata.hasAlpha) {
// 투명도 있음, PNG 사용
image = image.png();
} else {
// 투명도 없음, JPEG 사용
image = image.jpeg({ quality: 80, progressive: true });
}
await image.toFile(outputPath);
}프로그레시브 JPEG
javascript
await sharp('input.jpg')
.jpeg({
quality: 80,
progressive: true,
mozjpeg: true
})
.toFile('output.jpg');일괄 고급 처리
일괄 워터마크
javascript
const fs = require('fs').promises;
async function batchWatermark(inputDir, outputDir, watermarkPath) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
await sharp(path.join(inputDir, file))
.composite([
{
input: watermarkPath,
top: 10,
left: 10
}
])
.jpeg({ quality: 80 })
.toFile(path.join(outputDir, `watermarked_${file}`));
console.log(`워터마크 추가 완료: ${file}`);
} catch (error) {
console.error(`처리 실패 ${file}:`, error.message);
}
}
}
}일괄 형식 변환 및 최적화
javascript
async function batchOptimize(inputDir, outputDir) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
const metadata = await sharp(path.join(inputDir, file)).metadata();
const image = sharp(path.join(inputDir, file));
// 이미지 특성에 따라 최적 형식 선택
if (metadata.hasAlpha) {
await image.png({ compressionLevel: 9 }).toFile(path.join(outputDir, file.replace(/\.[^.]+$/, '.png')));
} else {
await image.jpeg({ quality: 80, progressive: true }).toFile(path.join(outputDir, file.replace(/\.[^.]+$/, '.jpg')));
}
console.log(`최적화 완료: ${file}`);
} catch (error) {
console.error(`처리 실패 ${file}:`, error.message);
}
}
}
}