예제
다양한 사용 사례의 실용적인 예제 및 코드 스니펫
이 섹션에서는 Qwen Image Edit 를 사용하여 다양한 이미지 편집 작업을 수행하는 방법에 대한 실용적인 예제를 제공합니다. 이러한 예제는 API 의 기능을 보여주고 자체 프로젝트에서 시작하는 데 도움이 되도록 설계되었습니다.
1. 기본 텍스트 편집
텍스트 수정
이미지 내의 기존 텍스트를 변경합니다.
// JavaScript/TypeScript
async function modifyText() {
const imageUrl = 'https://example.com/image-with-text.jpg';
const textToFind = 'Original Text';
const textToReplace = 'New Text';
try {
const result = await client.editText({
imageUrl,
textToFind,
textToReplace,
});
console.log('Modified image URL:', result.editedImageUrl);
} catch (error) {
console.error('Error modifying text:', error);
}
}
modifyText();
텍스트 번역
이미지 내의 텍스트를 다른 언어로 번역합니다.
// JavaScript/TypeScript
async function translateText() {
const imageUrl = 'https://example.com/image-with-english-text.jpg';
const textToFind = 'Hello World';
const targetLanguage = 'ko'; // 한국어
try {
const result = await client.editText({
imageUrl,
textToFind,
targetLanguage,
});
console.log('Translated image URL:', result.editedImageUrl);
n} catch (error) {
console.error('Error translating text:', error);
}
}
translateText();
텍스트 교정
이미지 내의 오타 또는 문법 오류를 수정합니다.
// JavaScript/TypeScript
async function correctText() {
const imageUrl = 'https://example.com/image-with-typo.jpg';
const textToFind = 'teh';
const textToReplace = 'the';
try {
const result = await client.editText({
imageUrl,
textToFind,
textToReplace,
});
console.log('Corrected image URL:', result.editedImageUrl);
} catch (error) {
console.error('Error correcting text:', error);
}
}
correctText();
2. 요소 추가
로고 추가
이미지에 회사 로고를 오버레이합니다.
// JavaScript/TypeScript
async function addLogo() {
const imageUrl = 'https://example.com/product-photo.jpg';
const logoUrl = 'https://example.com/your-company-logo.png';
try {
const result = await client.addElement({
imageUrl,
elementType: 'logo',
elementUrl: logoUrl,
position: { x: 50, y: 50 }, // 픽셀 단위
scale: 0.2, // 원본 크기의 20%
});
console.log('Image with logo URL:', result.editedImageUrl);
} catch (error) {
console.error('Error adding logo:', error);
}
}
addLogo();
워터마크 추가
이미지를 보호하기 위해 워터마크를 추가합니다.
// JavaScript/TypeScript
async function addWatermark() {
const imageUrl = 'https://example.com/original-artwork.jpg';
const watermarkText = 'CONFIDENTIAL';
try {
const result = await client.addElement({
imageUrl,
elementType: 'watermark',
text: watermarkText,
opacity: 0.5,
fontSize: 30,
color: '#FFFFFF',
});
console.log('Image with watermark URL:', result.editedImageUrl);
} catch (error) {
console.error('Error adding watermark:', error);
}
}
addWatermark();
가격표 추가
전자상거래 제품 이미지에 가격표를 동적으로 추가합니다.
// JavaScript/TypeScript
async function addPriceTag() {
const imageUrl = 'https://example.com/product-shoe.jpg';
const priceText = '$99.99';
try {
const result = await client.addElement({
imageUrl,
elementType: 'priceTag',
text: priceText,
position: { x: 100, y: 200 },
backgroundColor: '#FF0000',
color: '#FFFFFF',
});
console.log('Image with price tag URL:', result.editedImageUrl);
} catch (error) {
console.error('Error adding price tag:', error);
}
}
addPriceTag();
정보 요소 추가
이미지에 설명 텍스트 또는 콜아웃을 추가합니다.
// JavaScript/TypeScript
async function addInfoElement() {
const imageUrl = 'https://example.com/diagram.png';
const infoText = 'Key Feature A';
try {
const result = await client.addElement({
imageUrl,
elementType: 'infoBox',
text: infoText,
position: { x: 300, y: 150 },
borderColor: '#0000FF',
});
console.log('Image with info element URL:', result.editedImageUrl);
} catch (error) {
console.error('Error adding info element:', error);
}
}
addInfoElement();
3. 고급 스타일 전송
예술적 스타일 전송
이미지에 유명한 예술 작품의 스타일을 적용합니다.
// JavaScript/TypeScript
async function applyArtisticStyle() {
const imageUrl = 'https://example.com/my-photo.jpg';
const styleImageUrl = 'https://example.com/van-gogh-starry-night.jpg';
try {
const result = await client.transferStyle({
imageUrl,
styleImageUrl,
strength: 0.8, // 스타일 적용 강도
});
console.log('Image with artistic style URL:', result.editedImageUrl);
} catch (error) {
console.error('Error applying artistic style:', error);
}
}
applyArtisticStyle();
사진 스타일 전송
이미지에 다른 사진의 색상 및 톤 스타일을 적용합니다.
// JavaScript/TypeScript
async function applyPhotographicStyle() {
const imageUrl = 'https://example.com/daylight-photo.jpg';
const styleImageUrl = 'https://example.com/sunset-photo.jpg';
try {
const result = await client.transferStyle({
imageUrl,
styleImageUrl,
strength: 0.6,
});
console.log('Image with photographic style URL:', result.editedImageUrl);
} catch (error) {
console.error('Error applying photographic style:', error);
}
}
applyPhotographicStyle();
4. 일괄 처리
전자상거래 카탈로그 업데이트
제품 카탈로그의 모든 이미지에 프로모션 배너를 추가합니다.
// JavaScript/TypeScript
async function batchUpdateCatalog(productImageUrls) {
const bannerUrl = 'https://example.com/sale-banner.png';
const editPromises = productImageUrls.map(url =>
client.addElement({
imageUrl: url,
elementType: 'banner',
elementUrl: bannerUrl,
position: { x: 0, y: 0 },
})
);
try {
const results = await Promise.all(editPromises);
results.forEach(result => console.log('Processed image URL:', result.editedImageUrl));
} catch (error) {
console.error('Error batch updating catalog:', error);
}
}
// 사용 예시
// const productImages = ['url1.jpg', 'url2.jpg', 'url3.jpg'];
// batchUpdateCatalog(productImages);
다국어 현지화
여러 언어로 된 광고 캠페인을 위해 이미지 내의 텍스트를 일괄 번역합니다.
// JavaScript/TypeScript
async function batchLocalizeAds(adImageUrls, translations) {
// translations: [{ imageUrl, textToFind, targetLanguage }, ...]
const editPromises = translations.map(t =>
client.editText({
imageUrl: t.imageUrl,
textToFind: t.textToFind,
targetLanguage: t.targetLanguage,
})
);
try {
const results = await Promise.all(editPromises);
results.forEach(result => console.log('Localized image URL:', result.editedImageUrl));
} catch (error) {
console.error('Error batch localizing ads:', error);
}
}
// 사용 예시
// const adData = [
// { imageUrl: 'ad1.jpg', textToFind: 'Buy Now', targetLanguage: 'es' },
// { imageUrl: 'ad2.jpg', textToFind: 'Limited Offer', targetLanguage: 'fr' },
// ];
// batchLocalizeAds(adData);
5. 특정 사용 사례
전자상거래: 계절별 변형
계절별 테마에 맞게 제품 이미지에 눈송이 또는 나뭇잎과 같은 요소를 추가합니다.
// JavaScript/TypeScript
async function addSeasonalElements(productImageUrl, season) {
let elementUrl;
if (season === 'winter') {
elementUrl = 'https://example.com/snowflake.png';
} else if (season === 'autumn') {
elementUrl = 'https://example.com/autumn-leaf.png';
}
try {
const result = await client.addElement({
imageUrl: productImageUrl,
elementType: 'overlay',
elementUrl: elementUrl,
position: { x: 10, y: 10 },
opacity: 0.7,
});
console.log(`Image with ${season} element URL:`, result.editedImageUrl);
} catch (error) {
console.error(`Error adding ${season} element:`, error);
}
}
// addSeasonalElements('https://example.com/sweater.jpg', 'winter');
교육: 학습 자료 조정
다이어그램에 주석을 추가하거나 교육용 이미지의 텍스트를 단순화합니다.
// JavaScript/TypeScript
async function annotateDiagram(diagramUrl, annotationText, position) {
try {
const result = await client.addElement({
imageUrl: diagramUrl,
elementType: 'annotation',
text: annotationText,
position: position,
backgroundColor: '#FFFF00',
color: '#000000',
});
console.log('Annotated diagram URL:', result.editedImageUrl);
} catch (error) {
console.error('Error annotating diagram:', error);
}
}
// annotateDiagram('https://example.com/biology-diagram.png', 'Mitochondria: Powerhouse of the cell', { x: 200, y: 100 });
소셜 미디어: 다양한 플랫폼에 맞게 콘텐츠 최적화
다양한 소셜 미디어 플랫폼 (예: Instagram, Twitter) 에 맞게 이미지 크기를 조정하고 텍스트를 조정합니다.
// JavaScript/TypeScript
async function optimizeForSocialMedia(originalImageUrl, platform) {
let targetWidth, targetHeight;
if (platform === 'instagram') {
targetWidth = 1080; targetHeight = 1080; // 정사각형
} else if (platform === 'twitter') {
targetWidth = 1200; targetHeight = 675; // 16:9
}
try {
// 먼저 크기 조정
const resizedResult = await client.resizeImage({
imageUrl: originalImageUrl,
width: targetWidth,
height: targetHeight,
});
// 그런 다음 텍스트 조정 (예시: 플랫폼별 해시태그 추가)
const finalResult = await client.editText({
imageUrl: resizedResult.editedImageUrl,
textToFind: '#originalhashtag',
textToReplace: `#${platform} #newhashtag`,
});
console.log(`Optimized for ${platform} URL:`, finalResult.editedImageUrl);
} catch (error) {
console.error(`Error optimizing for ${platform}:`, error);
}
}
// optimizeForSocialMedia('https://example.com/event-poster.jpg', 'instagram');
6. 워크플로 자동화
콘텐츠 파이프라인
이미지 분석, 편집 및 게시를 포함하는 자동화된 콘텐츠 파이프라인을 구축합니다.
// JavaScript/TypeScript
async function automatedContentPipeline(newImageUrl) {
try {
// 1. 이미지 분석
const analysisResult = await client.analyzeImage({
imageUrl: newImageUrl,
features: ['text', 'objects'],
});
console.log('Analysis Result:', analysisResult);
// 2. 조건부 편집 (예: 특정 개체가 감지되면 워터마크 추가)
let processedImageUrl = newImageUrl;
if (analysisResult.objects.includes('person')) {
const watermarkResult = await client.addElement({
imageUrl: newImageUrl,
elementType: 'watermark',
text: 'Protected Content',
});
processedImageUrl = watermarkResult.editedImageUrl;
}
// 3. 텍스트 번역 (감지된 텍스트가 있는 경우)
if (analysisResult.text && analysisResult.text.length > 0) {
const translatedResult = await client.editText({
imageUrl: processedImageUrl,
textToFind: analysisResult.text[0].content,
targetLanguage: 'es',
});
processedImageUrl = translatedResult.editedImageUrl;
}
console.log('Final processed image URL:', processedImageUrl);
// 4. 게시 또는 저장 (예: 클라우드 스토리지에 업로드)
} catch (error) {
console.error('Error in automated content pipeline:', error);
}
}
// automatedContentPipeline('https://example.com/new-upload.jpg');
7. 성능 최적화
지능형 캐싱
자주 요청되는 이미지 및 편집 결과를 캐싱하여 응답 시간을 개선하고 API 호출을 줄입니다.
// JavaScript/TypeScript (개념적 예시)
const cache = new Map();
async function getOrEditImage(params) {
const cacheKey = JSON.stringify(params);
if (cache.has(cacheKey)) {
console.log('Serving from cache');
return cache.get(cacheKey);
}
const result = await client.editText(params); // 또는 다른 편집 작업
cache.set(cacheKey, result);
return result;
}
재시도 및 회로 차단기
일시적인 오류에 대한 견고성을 높이기 위해 재시도 로직과 회로 차단기 패턴을 구현합니다.
// JavaScript/TypeScript (개념적 예시, 'p-retry' 라이브러리 사용)
import pRetry from 'p-retry';
async function reliableEditText(params) {
return pRetry(() => client.editText(params), {
retries: 3, // 3회 재시도
onFailedAttempt: error => {
console.warn(`Attempt ${error.attemptNumber} failed. Retrying...`);
},
});
}
// reliableEditText({ imageUrl: '...', textToFind: '...', textToReplace: '...' });