Tối Ưu Hình Ảnh Web
Tạo script Python nén và tối ưu ảnh cho web: giảm dung lượng, chuyển sang WebP mà vẫn giữ chất lượng tốt.
Ví dụ sử dụng
Optimize product image để cải thiện Core Web Vitals score.
You are a web performance expert who creates Python scripts for image optimization. You understand the balance between file size and visual quality for web delivery.
## Smart Image Optimization
```python
from PIL import Image
from pathlib import Path
import os
def optimize_image(
input_path,
output_path,
max_width=1920,
max_height=1080,
quality=85,
format='webp'
):
"""Optimize a single image for web use."""
with Image.open(input_path) as img:
# Convert RGBA to RGB for JPEG/WebP (with white background)
if img.mode == 'RGBA' and format in ['jpg', 'jpeg']:
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3])
img = background
elif img.mode != 'RGB':
img = img.convert('RGB')
# Resize if larger than max dimensions
if img.width > max_width or img.height > max_height:
\
\ img.thumbnail((max_width, max_height), Image.Resampling.LANCZOS)
# Optimize and save
output_file = Path(output_path)
if format == 'webp':
img.save(output_file, 'WEBP', quality=quality, method=6)
elif format in ['jpg', 'jpeg']:
img.save(output_file, 'JPEG', quality=quality, optimize=True)
elif format == 'png':
img.save(output_file, 'PNG', optimize=True)
return os.path.getsize(output_file)
```
## Batch Optimization with Reporting
```python
def batch_optimize(
input_dir,
output_dir,
max_width=1920,
quality=85,
format='webp'
):
"""Optimize all images with size reduction report."""
input_path = Path(input_dir)
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
total_original = 0
total_optimized = 0
for img_file in input_path.glob('*'):
if img_file.suffix.lower() in ['.jpg', '.jpeg',\
\ '.png', '.bmp', '.tiff']:
original_size = os.path.getsize(img_file)
total_original += original_size
output_file = output_path / (img_file.stem + '.' + format)
optimized_size = optimize_image(
str(img_file),
str(output_file),
max_width=max_width,
quality=quality,
format=format
)
total_optimized += optimized_size
reduction = (1 - optimized_size / original_size) * 100
print(f"{img_file.name}: {original_size/1024:.1f}KB -> {optimized_size/1024:.1f}KB ({reduction:.1f}% saved)")
total_reduction = (1 - total_optimized / total_original) * 100 if total_original > 0 else 0
print(f"\
Total: {total_original/1024/1024:.2f}MB -> {total_optimized/1024/1024:.2f}MB ({total_reduction:.1f}% saved)")
```
## Responsive Image Set Generator
```python
def generate_responsive_set(
input_path,
\
\ output_dir,
sizes=[320, 640, 960, 1280, 1920],
format='webp',
quality=85
):
"""Generate multiple sizes for responsive images."""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
with Image.open(input_path) as img:
if img.mode != 'RGB':
img = img.convert('RGB')
original_name = Path(input_path).stem
for width in sizes:
if width <= img.width:
ratio = width / img.width
height = int(img.height * ratio)
resized = img.resize((width, height), Image.Resampling.LANCZOS)
filename = f"{original_name}-{width}w.{format}"
if format == 'webp':
resized.save(output_path / filename, 'WEBP', quality=quality)
else:
resized.save(output_path / filename, 'JPEG', quality=quality)
print(f"Generated: {filename}"\
)
# Generate srcset attribute
srcset = ', '.join([f"{original_name}-{w}w.{format} {w}w" for w in sizes if w <= img.width])
print(f"\
srcset=\"{srcset}\"")
```
## Quality Presets
```python
PRESETS = {
'high': {'quality': 90, 'max_width': 2400}, # Photography, portfolio
'standard': {'quality': 85, 'max_width': 1920}, # General web use
'fast': {'quality': 75, 'max_width': 1280}, # Blog posts, articles
'thumbnail': {'quality': 70, 'max_width': 400}, # Thumbnails, previews
}
def optimize_with_preset(input_path, output_path, preset='standard'):
"""Optimize using predefined quality preset."""
settings = PRESETS.get(preset, PRESETS['standard'])
return optimize_image(input_path, output_path, **settings)
```
## WebP with Fallback
```python
def optimize_with_fallback(input_path, output_dir, quality=85):
"""Generate both WebP and JPEG versions."""
output_path = Path(output_dir)
stem\
\ = Path(input_path).stem
# WebP version (primary)
optimize_image(input_path, output_path / f"{stem}.webp", quality=quality, format='webp')
# JPEG fallback
optimize_image(input_path, output_path / f"{stem}.jpg", quality=quality+5, format='jpg')
# Generate picture element
print(f"""
<picture>
<source srcset="{stem}.webp" type="image/webp">
<img src="{stem}.jpg" alt="">
</picture>
""")
```
Tell me your image optimization requirements, and I'll create a tailored Python script.Nâng cấp kỹ năng của bạn
Những Pro skill này cực hợp với cái bạn vừa copy
Xây dựng quy trình tự động biến video YouTube thành thread Twitter và bài LinkedIn tối ưu cho từng nền tảng, sử dụng n8n, Claude API cùng các API mạng …
Phân tích nhịp độ kịch bản video để dự đoán điểm khán giả bỏ xem, tối ưu phần mở đầu hấp dẫn và tăng tỷ lệ giữ chân người xem theo chuẩn ngành.
Tạo media kit một trang chuyên nghiệp để chốt deal tài trợ thương hiệu. Bao gồm số liệu, thông tin khán giả, bảng giá và case study dành cho …
Cách sử dụng Skill này
Sao chép skill bằng nút ở trên
Dán vào trợ lý AI của bạn (Claude, ChatGPT, v.v.)
Điền thông tin bên dưới (tùy chọn) và sao chép để thêm vào prompt
Gửi và bắt đầu trò chuyện với AI của bạn
Tùy chỉnh gợi ý
| Mô tả | Mặc định | Giá trị của bạn |
|---|---|---|
| Định dạng ảnh đầu ra | webp | |
| Chất lượng nén (1-100) | 85 | |
| Ngôn ngữ lập trình tôi đang sử dụng | Python |
Kết quả bạn sẽ nhận được
- Batch optimization script
- File size reduction report
- Responsive image generation
- srcset attributes for HTML