#!/bin/bash
# 设置字体路径
font_path="/storage/emulated/0/字体/黑体.ttf"
# 设置保存图片的目录
image_directory="/storage/emulated/0/图片"
# 定义生成文本图片的函数
generate_text_images() {
current_time=$(date +"%Y-%m-%d_%H:%M:%S")
image_width=1920
image_height=1080
max_chars_per_line=30
image_number=1
mkdir -p "$image_directory"
colors=("red" "green" "blue" "yellow" "orange")
num_colors=${#colors[@]}
cd "$image_directory" || exit
while IFS= read -r line; do
if [ ! -z "$line" ]; then
truncated_text=$(echo "$line" | sed -E "s/(.{1,$max_chars_per_line}[。?!……;]+)\s*/\1\n/g")
IFS=$'\n'
for text_line in $truncated_text; do
text_line=$(echo "$text_line" | sed -E "s/[。?!……;]+/\n/g")
rand_index=$(($RANDOM % num_colors))
bg_color=${colors[$rand_index]}
text_color="white"
text_length=${#text_line}
scale_factor=$(bc <<< "scale=2;$image_width * 0.7 / ($text_length * 36)")
convert -size "${image_width}x${image_height}" xc:black -font "$font_path" -pointsize "$(bc <<< "scale=0; 36 * $scale_factor")" -interword-spacing 10 -fill "$text_color" -gravity center -annotate 0 "$text_line" -extent "${image_width}x${image_height}" "${image_number}_文本_${bg_color}_${current_time}.jpg"
echo "${image_number}.${text_line} ${bg_color}${current_time}"
((image_number++))
done
fi
done
}
generate_text_images
# 打印
jk
convert: unable to open image '1_文本_blue_2024-05-17_12:42:31.jpg': Operation not permitted @ error/blob.c/OpenBlob/3596.
1.jk blue2024-05-17_12:42:31
我的代码没问题
#!/bin/bash
# 设置字体路径
font_path="/storage/emulated/0/字体/黑体.ttf"
# 设置保存图片的目录
image_directory="/storage/emulated/0/图片"
# 定义生成文本图片的函数
generate_text_images() {
# 获取当前时间戳
current_time=$(date +"%Y-%m-%d_%H:%M:%S")
# 定义图片尺寸
image_width=1920
image_height=1080
# 定义最大每行容纳字数
max_chars_per_line=30
# 设定图片编号
image_number=1
# 创建保存图片的目录
mkdir -p "$image_directory"
# 随机生成5种颜色背景与文字颜色
colors=("red" "green" "blue" "yellow" "orange")
num_colors=${#colors[@]}
# 切换到图片目录下
cd "$image_directory" || return
# 遍历输入的文本行
while IFS= read -r line; do
if [[ ! -z "$line" ]]; then
# 从标点符号处截断文本
truncated_text=$(echo "$line" | sed -E "s/(.{1,$max_chars_per_line}[。?!……;]+)\s*/\1\n/g")
# 按照换行符分割文本并处理每行文本
IFS=$'\n'
for text_line in $truncated_text; do
# 替换标点符号为换行符
text_line=$(echo "$text_line" | sed -E "s/[。?!……;]+/\n/g")
# 随机选择背景颜色和文字颜色
rand_index=$((RANDOM % num_colors))
bg_color=${colors[$rand_index]}
text_color="white"
# 计算放大比例
text_length=${#text_line}
scale_factor=$(bc <<< "scale=2;$image_width * 0.7 / ($text_length * 36)")
# 生成黑底白字图片
convert -size "${image_width}x${image_height}" xc:black -font "$font_path" -pointsize "$(bc <<< "scale=0; 36 * $scale_factor")" -interword-spacing 10 -fill "$text_color" -gravity center -annotate 0 "$text_line" -extent "${image_width}x${image_height}" "${image_number}_文本_${bg_color}_${current_time}.jpg"
echo "${image_number}.${text_line} ${bg_color}${current_time}"
# 增加图片编号
((image_number++))
done
fi
done
}
# 从标准输入读取多行文本,并调用生成文本图片的函数generate_text_images
generate_text_images