Ví dụ
Các ví dụ thực tế và đoạn mã cho các trường hợp sử dụng khác nhau
Ví dụ sử dụng Qwen Image Edit
Phần này cung cấp các ví dụ thực tế về cách sử dụng Qwen Image Edit cho nhiều tác vụ chỉnh sửa hình ảnh khác nhau. Bạn sẽ tìm thấy các ví dụ về chỉnh sửa văn bản, thêm yếu tố, chuyển đổi kiểu, xử lý hàng loạt và các trường hợp sử dụng cụ thể.
1. Chỉnh sửa văn bản cơ bản
Sửa đổi, dịch hoặc sửa lỗi văn bản trên hình ảnh.
Ví dụ 1.1: Sửa đổi văn bản hiện có
// JavaScript/TypeScript
async function modifyExistingText() {
try {
const result = await client.edit({
image: 'https://example.com/image-with-old-text.jpg',
prompt: 'Thay đổi văn bản "Chào mừng" thành "Xin chào thế giới"',
});
console.log('Hình ảnh đã chỉnh sửa có sẵn tại:', result.edited_image_url);
} catch (error) {
console.error('Lỗi khi chỉnh sửa văn bản:', error);
}
}
modifyExistingText();
Ví dụ 1.2: Dịch văn bản
# Python
def translateTextInImage():
try:
result = client.edit(
image='https://example.com/image-with-english-text.jpg',
prompt='Dịch văn bản "Sale" sang tiếng Tây Ban Nha',
)
print(f"Hình ảnh đã chỉnh sửa có sẵn tại: {result.edited_image_url}")
except Exception as e:
print(f"Lỗi khi dịch văn bản: {e}")
translateTextInImage()
Ví dụ 1.3: Sửa lỗi chính tả
// PHP
<?php
require 'vendor/autoload.php';
use QwenImageEdit\QwenImageEdit;
$client = new QwenImageEdit([
'apiKey' => 'YOUR_API_KEY',
'region' => 'YOUR_REGION',
]);
try {
$result = $client->edit([
'image' => 'https://example.com/image-with-typo.jpg',
'prompt' => 'Sửa lỗi chính tả "recieve" thành "receive"',
]);
echo 'Hình ảnh đã chỉnh sửa có sẵn tại: ' . $result['edited_image_url'] . "\n";
} catch (Exception $e) {
echo 'Lỗi khi sửa lỗi chính tả: ' . $e->getMessage() . "\n";
}
?>
2. Thêm và thao tác yếu tố
Thêm logo, hình mờ, nhãn giá hoặc các yếu tố thông tin khác.
Ví dụ 2.1: Thêm logo
// Java
import com.qwen.imageedit.QwenImageEditClient;
import com.qwen.imageedit.models.EditRequest;
public class AddLogo {
public static void main(String[] args) {
QwenImageEditClient client = new QwenImageEditClient("YOUR_API_KEY", "YOUR_REGION");
EditRequest request = new EditRequest()
.setImage("https://example.com/product-photo.jpg")
.setPrompt("Thêm logo công ty vào góc dưới bên phải")
.setElements(Arrays.asList(
new Element().setType("image").setSrc("https://example.com/my-logo.png").setPosition("bottom-right")
));
try {
EditResponse response = client.edit(request);
System.out.println("Hình ảnh đã chỉnh sửa có sẵn tại: " + response.getEditedImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Ví dụ 2.2: Thêm nhãn giá
// Go
package main
import (
"context"
"fmt"
"log"
qwenimageedit "github.com/qwen-image-edit/sdk/go"
)
func main() {
client := qwenimageedit.NewClient("YOUR_API_KEY", "YOUR_REGION")
resp, err := client.Edit(context.Background(), &qwenimageedit.EditRequest{
Image: "https://example.com/product-item.jpg",
Prompt: "Thêm nhãn giá $29.99 vào góc trên bên phải",
Elements: []qwenimageedit.Element{{
Type: "text",
Content: "$29.99",
Position: "top-right",
Style: map[string]interface{}{"color": "red", "fontSize": 24},
}},
})
if err != nil {
log.Fatalf("Lỗi chỉnh sửa: %v", err)
}
fmt.Printf("Hình ảnh đã chỉnh sửa có sẵn tại: %s\n", resp.EditedImageUrl)
}
3. Chuyển đổi kiểu nâng cao
Áp dụng các kiểu nghệ thuật hoặc nhiếp ảnh cho hình ảnh của bạn.
Ví dụ 3.1: Áp dụng kiểu nghệ thuật
# Ruby
require 'qwen_image_edit'
client = QwenImageEdit::Client.new(api_key: 'YOUR_API_KEY', region: 'YOUR_REGION')
begin
result = client.edit(
image: 'https://example.com/my-photo.jpg',
prompt: 'Áp dụng kiểu nghệ thuật như tranh Van Gogh',
style_transfer: { preset: 'van_gogh' }
)
puts "Hình ảnh đã chỉnh sửa có sẵn tại: #{result.edited_image_url}"
rescue QwenImageEdit::Error => e
puts "Lỗi chuyển đổi kiểu: #{e.message}"
end
4. Xử lý hàng loạt
Chỉnh sửa nhiều hình ảnh cùng một lúc để tăng hiệu quả.
Ví dụ 4.1: Cập nhật danh mục thương mại điện tử
// JavaScript/TypeScript
async function batchUpdateProducts(imageUrls) {
const results = [];
for (const url of imageUrls) {
try {
const result = await client.edit({
image: url,
prompt: 'Thêm huy hiệu "Giảm giá 20%" vào góc trên bên trái',
});
results.push({ original: url, edited: result.edited_image_url });
} catch (error) {
console.error(`Lỗi khi xử lý ${url}:`, error);
results.push({ original: url, error: error.message });
}
}
console.log('Kết quả xử lý hàng loạt:', results);
}
batchUpdateProducts([
'https://example.com/product1.jpg',
'https://example.com/product2.jpg',
'https://example.com/product3.jpg',
]);
Ví dụ 4.2: Bản địa hóa nội dung đa ngôn ngữ
# Python
def batchLocalizeImages(image_text_pairs):
results = []
for item in image_text_pairs:
try:
result = client.edit(
image=item['image_url'],
prompt=f"Dịch văn bản '{item['original_text']}' sang tiếng Pháp"
)
results.append({'original': item['image_url'], 'edited': result.edited_image_url})
except Exception as e:
results.append({'original': item['image_url'], 'error': str(e)})
print("Kết quả bản địa hóa hàng loạt:", results)
batchLocalizeImages([
{'image_url': 'https://example.com/ad-en.jpg', 'original_text': 'Limited Offer'},
{'image_url': 'https://example.com/banner-en.jpg', 'original_text': 'New Collection'},
])
5. Các trường hợp sử dụng cụ thể
Ví dụ 5.1: Các biến thể thương mại điện tử theo mùa
Nhanh chóng cập nhật hình ảnh sản phẩm cho các mùa hoặc chương trình khuyến mãi khác nhau.
// JavaScript/TypeScript
async function seasonalProductUpdate(productImage, season) {
let prompt;
if (season === 'winter') {
prompt = 'Thêm tuyết nhẹ và hiệu ứng mùa đông vào hình ảnh.';
} else if (season === 'summer') {
prompt = 'Làm cho hình ảnh sáng hơn và có nắng hơn, thêm không khí mùa hè.';
}
try {
const result = await client.edit({
image: productImage,
prompt: prompt,
});
console.log(`${season} hình ảnh sản phẩm có sẵn tại:`, result.edited_image_url);
} catch (error) {
console.error('Lỗi khi cập nhật sản phẩm theo mùa:', error);
}
}
seasonalProductUpdate('https://example.com/dress.jpg', 'winter');
Ví dụ 5.2: Chú thích sơ đồ giáo dục
Thêm nhãn, mũi tên hoặc chú thích vào sơ đồ giáo dục.
# Python
def annotateDiagram(diagramImage, annotations):
elements = []
for ann in annotations:
if ann['type'] == 'text':
elements.append({'type': 'text', 'content': ann['text'], 'position': ann['position']})
elif ann['type'] == 'arrow':
elements.append({'type': 'shape', 'shape': 'arrow', 'start': ann['start'], 'end': ann['end']})
try:
result = client.edit(
image=diagramImage,
prompt='Thêm các chú thích đã chỉ định vào sơ đồ.',
elements=elements
)
print(f"Sơ đồ đã chú thích có sẵn tại: {result.edited_image_url}")
except Exception as e:
print(f"Lỗi khi chú thích sơ đồ: {e}")
annotateDiagram(
'https://example.com/biology-diagram.png',
[
{'type': 'text', 'text': 'Tế bào thực vật', 'position': 'top-left'},
{'type': 'arrow', 'start': [100, 100], 'end': [150, 150]}
]
)
Ví dụ 5.3: Tối ưu hóa nội dung mạng xã hội
Nhanh chóng tạo hình ảnh hấp dẫn cho mạng xã hội.
// PHP
<?php
require 'vendor/autoload.php';
use QwenImageEdit\QwenImageEdit;
$client = new QwenImageEdit([
'apiKey' => 'YOUR_API_KEY',
'region' => 'YOUR_REGION',
]);
try {
$result = $client->edit([
'image' => 'https://example.com/social-post-draft.jpg',
'prompt' => 'Làm cho hình ảnh này sống động và hấp dẫn hơn cho mạng xã hội, thêm lớp văn bản "Ưu đãi đặc biệt!"',
'elements' => [
['type' => 'text', 'content' => 'Ưu đãi đặc biệt!', 'position' => 'center', 'style' => ['fontSize' => 48, 'color' => 'white', 'backgroundColor' => 'rgba(0,0,0,0.5)']]
]
]);
echo 'Hình ảnh mạng xã hội đã tối ưu hóa có sẵn tại: ' . $result['edited_image_url'] . "\n";
} catch (Exception $e) {
echo 'Lỗi khi tối ưu hóa hình ảnh mạng xã hội: ' . $e->getMessage() . "\n";
}
?>
6. Tự động hóa quy trình làm việc
Tích hợp Qwen Image Edit vào quy trình làm việc hiện có của bạn để tự động hóa các tác vụ chỉnh sửa hình ảnh.
Ví dụ 6.1: Xử lý hình ảnh sau khi tải lên
Bạn có thể sử dụng các chức năng đám mây (ví dụ: AWS Lambda, Google Cloud Functions) hoặc webhook để tự động xử lý hình ảnh sau khi chúng được tải lên bộ lưu trữ đối tượng.
# Python (Ví dụ chức năng Lambda)
import json
import os
from qwen_image_edit_sdk import QwenImageEdit
client = QwenImageEdit(
api_key=os.environ.get("QWEN_IMAGE_EDIT_API_KEY"),
region=os.environ.get("QWEN_IMAGE_EDIT_REGION")
)
def lambda_handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
image_url = f"https://{bucket}.s3.amazonaws.com/{key}"
try:
result = client.edit(
image=image_url,
prompt='Thêm hình mờ nhỏ "Qwen AI" vào góc dưới bên phải.',
)
print(f"Hình ảnh {key} đã được xử lý. Hình ảnh đã chỉnh sửa: {result.edited_image_url}")
except Exception as e:
print(f"Lỗi khi xử lý hình ảnh {key}: {e}")
return {
'statusCode': 200,
'body': json.dumps('Hình ảnh đã được xử lý thành công!')
}
7. Tối ưu hóa hiệu suất
Các mẹo để cải thiện hiệu suất của các lệnh gọi API.
- Bộ nhớ đệm thông minh: Lưu trữ kết quả hình ảnh đã chỉnh sửa để tránh xử lý lặp lại.
- Xử lý lỗi mạnh mẽ với thử lại: Triển khai logic thử lại để xử lý các lỗi mạng tạm thời hoặc lỗi API.
// JavaScript/TypeScript (Ví dụ thử lại)
async function reliableEdit(imageUrl, prompt, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const result = await client.edit({
image: imageUrl,
prompt: prompt,
});
return result.edited_image_url;
} catch (error) {
console.warn(`Thử chỉnh sửa ${i + 1} thất bại. Đang thử lại...`, error);
if (i === retries - 1) throw error; // Ném lỗi nếu là lần thử cuối cùng
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // Tăng thời gian chờ theo cấp số nhân
}
}
}
reliableEdit('https://example.com/image.jpg', 'Chuyển sang đen trắng.')
.then(url => console.log('Hình ảnh đã chỉnh sửa thành công:', url))
.catch(err => console.error('Chỉnh sửa thất bại sau nhiều lần thử:', err));