1. Python(使用 Pillow)
依赖安装
首先,确保你已经安装了 Flask
和 Pillow
(Python 图像处理库):
pip install Flask Pillow
Python 示例代码:
from flask import Flask, request, send_file
from PIL import Image, ImageDraw, ImageFont
import io
app = Flask(__name__)
@app.route('/')
def index():
return '''
<form method="POST" enctype="multipart/form-data">
活动标题: <input type="text" name="title"><br>
活动时间: <input type="text" name="time"><br>
活动地点: <input type="text" name="location"><br>
头像上传: <input type="file" name="avatar"><br>
<input type="submit" value="生成海报">
</form>
'''
@app.route('/', methods=['POST'])
def generate_poster():
title = request.form.get('title', '活动标题')
time = request.form.get('time', '活动时间')
location = request.form.get('location', '活动地点')
avatar = request.files.get('avatar')
# 创建海报背景
width, height = 800, 600
img = Image.new('RGB', (width, height), color='white')
draw = ImageDraw.Draw(img)
# 加载字体
font = ImageFont.truetype("arial.ttf", 40)
# 绘制文字
draw.text((50, 50), f"活动名称:{title}", font=font, fill='black')
draw.text((50, 150), f"时间:{time}", font=font, fill='black')
draw.text((50, 250), f"地点:{location}", font=font, fill='black')
# 处理头像并插入海报
if avatar:
avatar_image = Image.open(avatar)
avatar_image = avatar_image.resize((100, 100))
img.paste(avatar_image, (width - 150, height - 150))
# 保存到内存并返回给用户
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0)
return send_file(img_byte_arr, mimetype='image/png', as_attachment=True, download_name="poster.png")
if __name__ == '__main__':
app.run(debug=True)
2. Node.js(使用 Sharp)
依赖安装
确保你安装了 express
和 sharp
(图像处理库):
npm install express sharp
Node.js 示例代码:
const express = require('express');
const sharp = require('sharp');
const multer = require('multer');
const path = require('path');
const app = express();
// 设置上传中间件
const upload = multer({ dest: 'uploads/' });
app.use(express.static('public'));
app.get('/', (req, res) => {
res.send(`
<form action="/" method="POST" enctype="multipart/form-data">
活动标题: <input type="text" name="title"><br>
活动时间: <input type="text" name="time"><br>
活动地点: <input type="text" name="location"><br>
头像上传: <input type="file" name="avatar"><br>
<input type="submit" value="生成海报">
</form>
`);
});
app.post('/', upload.single('avatar'), (req, res) => {
const { title, time, location } = req.body;
const avatarPath = req.file.path;
// 创建海报背景
sharp({
create: {
width: 800,
height: 600,
channels: 3,
background: { r: 255, g: 255, b: 255 }
}
})
.composite([
{ input: Buffer.from(`<svg width="800" height="600">
<text x="50" y="50" font-size="30" fill="black">活动名称:${title}</text>
<text x="50" y="150" font-size="30" fill="black">时间:${time}</text>
<text x="50" y="250" font-size="30" fill="black">地点:${location}</text>
</svg>`), top: 0, left: 0 }
])
.resize(800, 600)
.toBuffer()
.then(data => {
sharp(avatarPath)
.resize(100, 100)
.toBuffer()
.then(avatarData => {
sharp(data)
.composite([{ input: avatarData, top: 450, left: 650 }])
.toFile('output.png', (err, info) => {
if (err) {
return res.status(500).send(err);
}
res.sendFile(path.join(__dirname, 'output.png'));
});
});
})
.catch(err => {
res.status(500).send(err);
});
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
3. PHP(使用 GD 库)
PHP 示例代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 获取表单数据
$title = $_POST['title'];
$time = $_POST['time'];
$location = $_POST['location'];
$avatar = $_FILES['avatar'];
// 创建一个背景图
$width = 800;
$height = 600;
$image = imagecreatetruecolor($width, $height);
// 设置背景色
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
// 设置文本颜色
$black = imagecolorallocate($image, 0, 0, 0);
// 设置字体路径
$font = './arial.ttf';
// 添加文字
imagettftext($image, 20, 0, 50, 50, $black, $font, "活动名称:$title");
imagettftext($image, 20, 0, 50, 150, $black, $font, "时间:$time");
imagettftext($image, 20, 0, 50, 250, $black, $font, "地点:$location");
// 处理头像
$avatarImage = imagecreatefromstring(file_get_contents($avatar['tmp_name']));
$avatarResized = imagescale($avatarImage, 100, 100);
imagecopy($image, $avatarResized, 650, 450, 0, 0, 100, 100);
// 设置响应头
header('Content-Type: image/png');
imagepng($image);
// 销毁图像资源
imagedestroy($image);
imagedestroy($avatarResized);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>生成海报</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
活动标题: <input type="text" name="title"><br>
活动时间: <input type="text" name="time"><br>
活动地点: <input type="text" name="location"><br>
头像上传: <input type="file" name="avatar"><br>
<input type="submit" value="生成海报">
</form>
</body>
</html>
4. Java (使用 BufferedImage)
Java 示例代码:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PosterGenerator {
public static void main(String[] args) throws IOException {
// 创建一个 800x600 的白色背景
int width = 800, height = 600;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
// 设置背景色为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 设置字体和颜色
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 40));
// 添加文字
g.drawString("活动名称:我的活动", 50, 50);
g.drawString("时间:2025年1月1日", 50, 150);
g.drawString("地点:某地", 50, 250);
// 可以在这里插入
头像图像(假设你有一个头像文件) // BufferedImage avatar = ImageIO.read(new File(“avatar.png”)); // g.drawImage(avatar, 650, 450, 100, 100, null);
// 保存图片到本地文件
File outputFile = new File("poster.png");
ImageIO.write(image, "PNG", outputFile);
System.out.println("海报生成完成!");
}
}
### 5. **Go (使用 `github.com/nfnt/resize` 和 `github.com/fogleman/gg`)**
#### Go 示例代码:
```go
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"os"
"github.com/fogleman/gg"
"github.com/nfnt/resize"
)
func main() {
// 创建图像画布
width, height := 800, 600
img := image.NewRGBA(image.Rect(0, 0, width, height))
// 设置背景颜色
draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
// 创建图形上下文
context := gg.NewContextForRGBA(img)
// 设置字体和颜色
context.SetRGB(0, 0, 0)
context.SetFontFace(gg.NewFontFace("/usr/share/fonts/ubuntu/Ubuntu-Regular.ttf", 40))
// 添加文字
context.DrawStringAnchored("活动名称:我的活动", 50, 50, 0, 0)
context.DrawStringAnchored("时间:2025年1月1日", 50, 150, 0, 0)
context.DrawStringAnchored("地点:某地", 50, 250, 0, 0)
// 保存为PNG文件
outputFile, _ := os.Create("poster.png")
defer outputFile.Close()
png.Encode(outputFile, img)
fmt.Println("海报生成完成!")
}
总结
以上展示了如何使用不同的编程语言(Python, Node.js, PHP, Java, Go)和常用的图像处理库生成后端海报。
没有评论内容