#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --input <файл или папка> [--outdir <папка>] [--format png] [--color] [--force]" } input="" outdir="clean" format="png" color=0 force=0 while [[ $# -gt 0 ]]; do case "$1" in --input) input="${2:-}"; shift 2 ;; --outdir) outdir="${2:-}"; shift 2 ;; --format) format="${2:-}"; shift 2 ;; --color) color=1; shift ;; --force) force=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;; esac done if [[ -z "$input" || ! -e "$input" ]]; then echo "Укажите существующий файл или папку через --input" >&2 exit 2 fi case "$format" in png|jpg|tiff) ;; *) echo "Формат должен быть png, jpg или tiff" >&2; exit 2 ;; esac magick_bin="" if command -v magick >/dev/null 2>&1; then magick_bin="$(command -v magick)" elif command -v convert >/dev/null 2>&1; then magick_bin="$(command -v convert)" fi if [[ -z "$magick_bin" ]]; then echo "ImageMagick не найден. Нужна команда magick или convert." >&2 exit 2 fi files=() if [[ -f "$input" ]]; then files+=("$input") elif [[ -d "$input" ]]; then while IFS= read -r -d '' file; do files+=("$file") done < <(find "$input" -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.tif' -o -iname '*.tiff' -o -iname '*.bmp' \) -print0) else echo "Путь не является файлом или папкой: $input" >&2 exit 2 fi if [[ ${#files[@]} -eq 0 ]]; then echo "Изображения не найдены" >&2 exit 1 fi mkdir -p "$outdir" saved=0 failed=0 for source in "${files[@]}"; do name="$(basename "${source%.*}")" target="$outdir/${name}_clean.$format" if [[ -e "$target" && "$force" -eq 0 ]]; then echo "Пропуск, уже существует: $target" continue fi args=("$source" -auto-orient -deskew 40% -fuzz 5% -trim +repage -normalize) if [[ "$color" -eq 0 ]]; then args+=(-colorspace Gray) fi if [[ "$format" == "jpg" ]]; then args+=(-quality 92) elif [[ "$format" == "tiff" ]]; then args+=(-compress lzw) fi args+=("$target") if "$magick_bin" "${args[@]}"; then echo "Готово: $target" saved=$((saved + 1)) else echo "Не удалось обработать: $source" >&2 failed=$((failed + 1)) fi done echo "Обработано файлов: $saved, ошибок: $failed" [[ "$failed" -eq 0 ]]