Генератор изображений Python QR Code

Как написать Генератор изображений Python QR Code?

Я пишу:

import  qrcode

img = qrcode.make("https://ru.stackoverflow.com/questions/")
type(img)
img.save("some_file.png")

но никак не выходит как надо: файл не сохраняется как .png.


Ответы (1 шт):

Автор решения: S. Nick

Генерируйте QR-коды.

Для стандартной установки, которая будет включать pillow для создания изображений - запустите:

pip install qrcode[pil]

Ваш пример рабочий:

import  qrcode

img = qrcode.make("https://ru.stackoverflow.com/questions/")

print(f'{type(img)}')              #  <class 'qrcode.image.pil.PilImage'>

img.save("some_file.png")


А если вы хотите как-то визуализировать генератор изображений Python QR Code, вам в помощь PyQt — реализация фреймворка Qt для языка Python.

Прежде чем запустить мой пример, убедитесь, что вы установили PyQt5.

Установит его просто:

pip install PyQt5 
pip install pyqt5-tools

Теперь пробуйте:

main.py

import sys
import qrcode
from PIL.ImageQt import ImageQt
from PyQt5.Qt import *


class QRCodeApp(QWidget):
    def __init__(self):
        super().__init__()
        
        mainLayout = QVBoxLayout(self)
        
        label = QLabel("Enter text:")
        self.textEntry = QLineEdit()  
        entryLayout = QHBoxLayout()        
        entryLayout.addWidget(label)
        entryLayout.addWidget(self.textEntry)
        mainLayout.addLayout(entryLayout)
        
        self.buttonGenerate = QPushButton('Generate QR Code')
        self.buttonGenerate.clicked.connect(self.create_qr_code)
        
        self.buttonSaveImage = QPushButton('Save QR Image')
        self.buttonSaveImage.clicked.connect(self.save_qr_code)
        
        self.buttonClear = QPushButton('Clear')
        self.buttonClear.clicked.connect(self.clear_fields)

        buttonLayout = QHBoxLayout()        
        buttonLayout.addWidget(self.buttonGenerate)
        buttonLayout.addWidget(self.buttonSaveImage)
        buttonLayout.addWidget(self.buttonClear)
        mainLayout.addLayout(buttonLayout)
        
        self.imageLabel = QLabel()
        self.imageLabel.setAlignment(Qt.AlignCenter)
        imageLayout = QVBoxLayout()
        imageLayout.addStretch()        
        imageLayout.addWidget(self.imageLabel)
        mainLayout.addLayout(imageLayout)
        
        self.statusBar = QStatusBar()
        mainLayout.addWidget(self.statusBar)
        
    def clear_fields(self):
        self.textEntry.clear()
        self.imageLabel.clear()
        self.statusBar.showMessage('')   
        
    def create_qr_code(self):
        text = self.textEntry.text()
        img = qrcode.make(text)
        qr = ImageQt(img)
        pix = QPixmap.fromImage(qr)
        self.imageLabel.setPixmap(pix)
        
    def save_qr_code(self):
        file_name = self.textEntry.text()
        if file_name:
            file_name = file_name.replace(":", "_")
            file_name = file_name.replace("/", "")
            path = f'{file_name}.png'            
            
            self.imageLabel.pixmap().save(f'{path}')
            
            self.statusBar.showMessage('Image is saved at {0}'.format(path))
        

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setFont(QFont("Open Sans", 16))
    app.setStyleSheet('QPushButton {height: 50px; font-size: 28px;}')
    mywin = QRCodeApp()
    mywin.resize(650, 600)
    mywin.show()
    sys.exit(app.exec_())

введите сюда описание изображения

введите сюда описание изображения

→ Ссылка