如何用脚本生成随机占位图

wen 实用脚本 1

本文目录导读:

如何用脚本生成随机占位图

  1. Python脚本(PIL库)
  2. JavaScript(Canvas)
  3. Shell脚本(使用ImageMagick)
  4. Node.js(使用sharp库)
  5. 命令行工具(基于Python)
  6. 使用建议

Python脚本(PIL库)

from PIL import Image, ImageDraw, ImageFont
import random
import colorsys
def random_color():
    """生成随机鲜艳颜色"""
    h = random.random()
    s = 0.5 + random.random() * 0.5
    v = 0.8 + random.random() * 0.2
    r, g, b = colorsys.hsv_to_rgb(h, s, v)
    return (int(r*255), int(g*255), int(b*255))
def create_placeholder(width=400, height=300, text=None):
    """生成占位图"""
    img = Image.new('RGB', (width, height), random_color())
    draw = ImageDraw.Draw(img)
    # 添加文字
    if text is None:
        text = f"{width}x{height}"
    # 使用默认字体
    font = ImageFont.load_default()
    # 文字居中
    text_bbox = draw.textbbox((0, 0), text, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    x = (width - text_width) / 2
    y = (height - text_height) / 2
    # 绘制文字
    draw.text((x, y), text, fill='white', font=font)
    # 添加边框
    draw.rectangle([0, 0, width-1, height-1], outline='white', width=2)
    return img
# 使用示例
img = create_placeholder(800, 600)
img.save('placeholder.png')

JavaScript(Canvas)

function generatePlaceholder(width, height, text) {
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    // 随机颜色
    const hue = Math.random() * 360;
    ctx.fillStyle = `hsl(${hue}, 60%, 50%)`;
    ctx.fillRect(0, 0, width, height);
    // 文字
    ctx.fillStyle = 'white';
    ctx.font = `${Math.min(width, height) * 0.08}px Arial`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    const displayText = text || `${width}x${height}`;
    ctx.fillText(displayText, width/2, height/2);
    // 边框
    ctx.strokeStyle = 'white';
    ctx.lineWidth = 2;
    ctx.strokeRect(1, 1, width-2, height-2);
    return canvas.toDataURL();
}
// 使用
const placeholderURL = generatePlaceholder(800, 600);
document.getElementById('myImage').src = placeholderURL;

Shell脚本(使用ImageMagick)

#!/bin/bash
generate_placeholder() {
    local width=${1:-400}
    local height=${2:-300}
    local text="${3:-${width}x${height}}"
    local output="${4:-placeholder.png}"
    # 生成随机颜色
    local r=$((RANDOM % 256))
    local g=$((RANDOM % 256))
    local b=$((RANDOM % 256))
    # 创建占位图
    convert -size ${width}x${height} \
            xc:"rgb($r,$g,$b)" \
            -font Arial \
            -pointsize $((height/10)) \
            -fill white \
            -gravity center \
            -annotate 0 "$text" \
            -stroke white -strokewidth 2 \
            -draw "rectangle 1,1 $((width-2)),$((height-2))" \
            "$output"
    echo "已生成: $output (${width}x${height})"
}
# 使用示例
generate_placeholder 800 600 "测试图片"

Node.js(使用sharp库)

const sharp = require('sharp');
async function createPlaceholder(width, height, text) {
    const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
        <rect width="100%" height="100%" 
              fill="hsl(${Math.random() * 360}, 60%, 50%)" 
              stroke="white" stroke-width="2"/>
        <text x="50%" y="50%" text-anchor="middle" 
              dy=".3em" fill="white" font-size="${Math.min(width, height) * 0.08}px">
            ${text || `${width}x${height}`}
        </text>
    </svg>`;
    const buffer = Buffer.from(svg);
    return sharp(buffer)
        .png()
        .toBuffer();
}
// 使用
createPlaceholder(800, 600).then(buffer => {
    require('fs').writeFileSync('placeholder.png', buffer);
});

命令行工具(基于Python)

创建可复用脚本 placeholder.py

#!/usr/bin/env python3
import sys
from PIL import Image, ImageDraw, ImageFont
import random
def main():
    if len(sys.argv) < 3:
        print("用法: python placeholder.py <宽度> <高度> [文字]")
        sys.exit(1)
    width = int(sys.argv[1])
    height = int(sys.argv[2])
    text = sys.argv[3] if len(sys.argv) > 3 else f"{width}x{height}"
    img = Image.new('RGB', (width, height), 
                    (random.randint(0,255), random.randint(0,255), random.randint(0,255)))
    draw = ImageDraw.Draw(img)
    # 添加文字
    font = ImageFont.load_default()
    text_bbox = draw.textbbox((0, 0), text, font=font)
    x = (width - (text_bbox[2] - text_bbox[0])) / 2
    y = (height - (text_bbox[3] - text_bbox[1])) / 2
    draw.text((x, y), text, fill='white', font=font)
    draw.rectangle([0, 0, width-1, height-1], outline='white', width=2)
    output = f"placeholder_{width}x{height}.png"
    img.save(output)
    print(f"已生成: {output}")
if __name__ == "__main__":
    main()

使用建议

  1. 在线服务:使用 https://placeholder.com 或 https://via.placeholder.com
  2. 快速原型:推荐使用浏览器端的JavaScript方法
  3. 批量生成:使用Python或Shell脚本
  4. 服务器端:使用Node.js + sharp库

选择哪种方法取决于你的技术栈和具体需求,需要更多定制化功能(如渐变、图案等)吗?

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