Help users batch convert file formats: image format conversion, document format conversion.
Use Cases
- User says "convert these HEIC photos to JPG", "PNG to WebP"
- User says "batch compress these images", "resize images"
- User says "Markdown to HTML", "batch convert formats"
Dependency Installation
Automatically installed on first use:
pip install Pillow
Execution Method
Process images via Python Pillow, handle other formats via bash.
Image Format Conversion
from PIL import Image
import os
input_dir = "/path/to/input"
output_dir = "/path/to/output"
target_format = "JPEG" # JPEG, PNG, WEBP, BMP, TIFF
os.makedirs(output_dir, exist_ok=True)
count = 0
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.heic', '.webp', '.bmp')):
img = Image.open(os.path.join(input_dir, filename))
# RGBA → RGB for JPEG
if img.mode == 'RGBA' and target_format == 'JPEG':
img = img.convert('RGB')
new_name = os.path.splitext(filename)[0] + ".jpg"
img.save(os.path.join(output_dir, new_name), target_format, quality=90)
count += 1
print(f"转换完成: {count} 个文件")
HEIC to JPG (macOS)
# macOS 原生支持 HEIC
for f in /path/to/*.HEIC; do
sips -s format jpeg "$f" --out "/path/to/output/$(basename "${f%.*}").jpg"
done
Batch Compress Images
from PIL import Image
import os
input_dir = "/path/to/input"
output_dir = "/path/to/compressed"
max_size = (1920, 1080)
quality = 80
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
img = Image.open(os.path.join(input_dir, filename))
img.thumbnail(max_size, Image.Resampling.LANCZOS)
if img.mode == 'RGBA':
img = img.convert('RGB')
img.save(os.path.join(output_dir, filename), quality=quality)
print("压缩完成")
Batch Resize Images
from PIL import Image
import os
target_width = 800
input_dir = "/path/to/input"
output_dir = "/path/to/resized"
os.makedirs(output_dir, exist_ok=True)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
img = Image.open(os.path.join(input_dir, filename))
ratio = target_width / img.width
new_height = int(img.height * ratio)
img = img.resize((target_width, new_height), Image.Resampling.LANCZOS)
img.save(os.path.join(output_dir, filename))
Markdown → HTML
# 使用 Python 内置
python3 -c "
import markdown
with open('/path/to/input.md') as f:
html = markdown.markdown(f.read(), extensions=['tables', 'fenced_code'])
with open('/path/to/output.html', 'w') as f:
f.write(html)
print('转换完成')
"
Safety Rules
- Do not overwrite original files: output to a new directory
- Show file list before conversion: confirm the number and format of files to be converted
- Large batch operation reminder: remind the user to confirm when there are more than 100 files
Output Specifications
- Before conversion: list the number of files, source format, target format
- After conversion: report the number of successes/failures, output directory, total size change