Текст и документы
Прочитать QR-код с картинки
Декодирует PNG и JPEG с QR-кодом через zbarimg и сохраняет текст в файл.
Shell
Linux
macOS
Средний
Что делает скрипт
Скрипт проверяет наличие zbarimg, обходит файлы по маске и выводит распознанный текст. Можно обработать одну картинку или папку, а режим --with-filename добавляет подписи перед результатом. Исходные изображения не изменяются.
Запуск
Быстрый старт
bash qr_decode.sh --input qr.png
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
Другие варианты
bash qr_decode.sh --input qr.pngbash qr_decode.sh --input ./images --pattern '*.png' --with-filenamebash qr_decode.sh --input ./images --pattern '*.jpg' --output decoded.txt
Что понадобится
Bash 4+
Стандартные find, basename, mktemp
Linux
sudo apt install bash
macOS
brew install bash
ZBar
Утилита zbarimg для чтения QR-кодов
Linux
sudo apt install zbar-tools
macOS
brew install zbar
Исходник
qr_decode.sh
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Использование: $0 --input <файл|папка> [--pattern '*.png'] [--output файл] [--with-filename]"
}
input=""
pattern="*.png"
output=""
with_name=0
while [[ $# -gt 0 ]]; do
case "$1" in
--input) input="${2:-}"; shift 2 ;;
--pattern) pattern="${2:-}"; shift 2 ;;
--output) output="${2:-}"; shift 2 ;;
--with-filename) with_name=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
if ! command -v zbarimg >/dev/null 2>&1; then
echo "Не найден zbarimg. Установите пакет zbar." >&2
exit 2
fi
if [[ -n "$output" && -f "$input" && "$output" == "$input" ]]; then
echo "Выходной файл совпадает с входным изображением" >&2
exit 2
fi
tmp_dir="$(mktemp -d)"
trap 'rm -rf -- "$tmp_dir"' EXIT
: > "$tmp_dir/result.txt"
found=0
failed=0
process_file() {
local file="$1"
local text
if ! text="$(zbarimg --quiet --raw -- "$file" 2>/dev/null)"; then
echo "Не удалось прочитать: $file" >&2
failed=$((failed + 1))
return 0
fi
if [[ -z "$text" ]]; then
echo "QR-код не найден: $file" >&2
failed=$((failed + 1))
return 0
fi
if [[ "$with_name" -eq 1 ]]; then
printf '=== %s ===\n' "$file" >> "$tmp_dir/result.txt"
fi
printf '%s\n' "$text" >> "$tmp_dir/result.txt"
found=$((found + 1))
}
if [[ -f "$input" ]]; then
process_file "$input"
else
while IFS= read -r -d '' file; do
process_file "$file"
done < <(find "$input" -type f -name "$pattern" -print0)
fi
if [[ -s "$tmp_dir/result.txt" ]]; then
if [[ -n "$output" ]]; then
cp -- "$tmp_dir/result.txt" "$output"
echo "Результат: $output" >&2
else
cat "$tmp_dir/result.txt"
fi
fi
echo "Распознано: $found, ошибок: $failed" >&2
if [[ "$found" -eq 0 ]]; then
exit 1
fi
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.