我使用了 qrcode 库来生成二维码。现在我想从中导出一串 1 和 0,黑色像素是
1
,白色像素是 0
,然后我将所有行与换行符连接在一起形成一个长字符串。
换句话说,它看起来像下面的图 4。我将如何生成它?
这里是生成二维码的代码:
import qrcode
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
data = "hello world!"
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(back_color=(255, 255, 255), fill_color=(0, 0, 0))
img.save("test.png")
通过尝试我得到的解决方法,但并不优雅
import qrcode
# Set the colors corresponding to 0 and 1 respectively, the default is black and white
qr = qrcode.QRCode(version=None, box_size=1, border=0,
error_correction=qrcode.constants.ERROR_CORRECT_L)
# The string to generate (can be any text)
data = "Hello, world!"
# Add the data of the QR code to be generated to the qr object
qr.add_data(data)
# Generate a QR code and save it as a PNG file
img = qr.make_image(fill_color="black", back_color="white")
img.save("qr_code.png")
# Convert QR code data to 01 string
qr_str = qr.get_matrix()
qr_str = '\n'.join([''.join([('1' if cell else '0') for cell in row]) for row in qr_str])
print(qr_str)