如何用脚本生成图片缩略图

wen 实用脚本 1

本文目录导读:

如何用脚本生成图片缩略图

  1. 使用 ImageMagick (最常用)
  2. 使用 OpenCV (Python)
  3. 使用 Node.js (Sharp)
  4. 批量处理并保持目录结构
  5. 安装依赖
  6. 使用建议

我来介绍几种生成图片缩略图的方法,包括命令行工具和脚本方案。

使用 ImageMagick (最常用)

Bash 脚本

#!/bin/bash
# 批量生成缩略图脚本
# 设置参数
INPUT_DIR="./images"
OUTPUT_DIR="./thumbnails"
THUMB_SIZE="200x200"
QUALITY=85
# 创建输出目录
mkdir -p "$OUTPUT_DIR"
# 批量处理图片
for img in "$INPUT_DIR"/*.{jpg,jpeg,png,gif,bmp}; do
    if [ -f "$img" ]; then
        filename=$(basename "$img")
        convert "$img" -resize "$THUMB_SIZE" -quality "$QUALITY" "$OUTPUT_DIR/$filename"
        echo "已生成: $filename"
    fi
done
echo "完成!"

Python 脚本 (使用 Pillow)

from PIL import Image
import os
from pathlib import Path
def create_thumbnails(input_dir, output_dir, size=(200, 200)):
    """生成缩略图"""
    # 创建输出目录
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    # 支持的图片格式
    extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
    for file in Path(input_dir).iterdir():
        if file.suffix.lower() in extensions:
            try:
                # 打开图片
                with Image.open(file) as img:
                    # 创建缩略图
                    img.thumbnail(size)
                    # 保存缩略图
                    output_path = Path(output_dir) / file.name
                    img.save(output_path, quality=85)
                    print(f"已生成: {file.name}")
            except Exception as e:
                print(f"处理 {file.name} 时出错: {e}")
# 使用示例
create_thumbnails("./images", "./thumbnails", (300, 300))

使用 OpenCV (Python)

import cv2
import os
from pathlib import Path
def create_thumbnails_opencv(input_dir, output_dir, size=(200, 200)):
    """使用 OpenCV 生成缩略图"""
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
    for file in Path(input_dir).iterdir():
        if file.suffix.lower() in extensions:
            try:
                # 读取图片
                img = cv2.imread(str(file))
                if img is None:
                    continue
                # 计算缩放比例
                h, w = img.shape[:2]
                scale = min(size[0]/w, size[1]/h)
                # 缩放图片
                new_size = (int(w * scale), int(h * scale))
                thumb = cv2.resize(img, new_size, interpolation=cv2.INTER_AREA)
                # 保存
                output_path = Path(output_dir) / file.name
                cv2.imwrite(str(output_path), thumb)
                print(f"已生成: {file.name}")
            except Exception as e:
                print(f"处理 {file.name} 时出错: {e}")
# 使用示例
create_thumbnails_opencv("./images", "./thumbnails", (300, 300))

使用 Node.js (Sharp)

const sharp = require('sharp');
const fs = require('fs').promises;
const path = require('path');
async function createThumbnails(inputDir, outputDir, size=200) {
    // 创建输出目录
    await fs.mkdir(outputDir, { recursive: true });
    // 读取文件列表
    const files = await fs.readdir(inputDir);
    const extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
    for (const file of files) {
        const ext = path.extname(file).toLowerCase();
        if (extensions.includes(ext)) {
            try {
                const inputPath = path.join(inputDir, file);
                const outputPath = path.join(outputDir, file);
                await sharp(inputPath)
                    .resize(size, size, {
                        fit: 'cover',
                        withoutEnlargement: true
                    })
                    .toFile(outputPath);
                console.log(`已生成: ${file}`);
            } catch (error) {
                console.error(`处理 ${file} 时出错:`, error.message);
            }
        }
    }
}
// 使用示例
createThumbnails('./images', './thumbnails', 300);

批量处理并保持目录结构

import os
from PIL import Image
from pathlib import Path
def batch_create_thumbnails_recursive(input_dir, output_dir, size=(200, 200)):
    """递归处理所有子目录的图片"""
    for root, dirs, files in os.walk(input_dir):
        # 计算相对路径
        relative_path = os.path.relpath(root, input_dir)
        current_output = Path(output_dir) / relative_path
        # 创建对应的输出目录
        current_output.mkdir(parents=True, exist_ok=True)
        for file in files:
            if file.lower().endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
                input_path = Path(root) / file
                try:
                    with Image.open(input_path) as img:
                        img.thumbnail(size)
                        output_path = current_output / file
                        img.save(output_path, quality=85)
                        print(f"已生成: {relative_path}/{file}")
                except Exception as e:
                    print(f"处理 {file} 时出错: {e}")
# 使用示例
batch_create_thumbnails_recursive("./images", "./thumbnails", (300, 300))

安装依赖

# ImageMagick (Ubuntu/Debian)
sudo apt-get install imagemagick
# Python Pillow
pip install Pillow
# OpenCV
pip install opencv-python
# Node.js sharp
npm install sharp

使用建议

  1. 保持宽高比:使用 thumbnail() 而不是 resize() 可以保持原始比例
  2. 批量处理:使用 concurrent.futuresthreading 并行处理大量图片
  3. 错误处理:添加适当的异常处理,避免脚本因个别文件问题中断
  4. 进度显示:处理大量图片时添加进度条
  5. 缓存机制:已处理的文件可以跳过,提高效率

选择哪种方法主要取决于你的使用场景和已有的开发环境。

抱歉,评论功能暂时关闭!