Может кому пригодится мой код, нужно было именно для такого же варианта форматирования. Пришлось сделать много улучшений, чтобы добиться идеального результата.
from PIL import Image
# QR-код
qr_text = """
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
"""
# Разделяем текст на строки и определяем размеры
lines = qr_text.strip().split('\n')
height = len(lines)
width = max(len(line) for line in lines)
# Создание изображения с удвоенной высотой
img_height = height * 2
img_width = width
img = Image.new('1', (img_width, img_height), 1) # Заполняем изображение белым цветом
# Заполнение изображения
for y_text, line in enumerate(lines):
for x_text, char in enumerate(line):
# Обрабатываем '1'
if char == '1':
if x_text < img_width:
if 2 * y_text < img_height:
img.putpixel((x_text, 2 * y_text), 0)
if 2 * y_text + 1 < img_height:
img.putpixel((x_text, 2 * y_text + 1), 0)
# Обрабатываем пробелы
elif char == ' ':
if x_text > 0 and x_text < len(line) - 1 and line[x_text - 1] == '1' and line[x_text + 1] == '1':
# Одиночный пробел между '1' - заполняем черным
if x_text < img_width:
if 2 * y_text < img_height:
img.putpixel((x_text, 2 * y_text), 0)
if 2 * y_text + 1 < img_height:
img.putpixel((x_text, 2 * y_text + 1), 0)
else:
# Обычный пробел - заполняем белым
if x_text < img_width:
if 2 * y_text < img_height:
img.putpixel((x_text, 2 * y_text), 1)
if 2 * y_text + 1 < img_height:
img.putpixel((x_text, 2 * y_text + 1), 1)
# Коррекция: однократное растягивание черных пикселей вправо
for y in range(img_height):
pixels_to_change = []
for x in range(img_width - 1):
if img.getpixel((x, y)) == 0 and img.getpixel((x + 1, y)) == 1:
pixels_to_change.append((x + 1, y))
for x, y_coord in pixels_to_change:
img.putpixel((x, y_coord), 0)
# Добавление вертикального ряда справа
new_img_width = img_width + 1
new_img = Image.new('1', (new_img_width, img_height), 1)
# Копирование пикселей из старого изображения
for x in range(img_width):
for y in range(img_height):
new_img.putpixel((x, y), img.getpixel((x, y)))
# Копирование пикселей из последнего столбца старого изображения в новый столбец
for y in range(img_height):
new_img.putpixel((img_width, y), img.getpixel((img_width - 1, y)))
new_img.save('qr_code.png')
new_img.show()