0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】URLをQRコードに変換してクリップボードへ保存するPythonスクリプトを生成した

Posted at

目次

はじめに

適当なURLをQRコードとしてクリップボードに保存するpythonスクリプトを作成した。
生成AIにコードを作成してもらう練習ついでに作ったが、流石に適当な指示一発ではできなかったものの複数回やり取りをしたら一応動作するコードができました。そのため今回ソースコードに関してはじっくりソースコードを眺めていないです。

インストール

必要に応じて以下のものをPythonと必要なライブラリをインストールする。
既にインストール済みであれば不要。

Pythonのインストール時はAdd Python to PATHの項目にチェックを入れるようにする。

インストール後は以下のコマンドで必要なライブラリをインストールする。

pip install qrcode[pil]
pip install pywin32

ソースコード

import win32clipboardの記載がある通りWindows OS向けのスクリプトになります。

URL2QRcode.py
import tkinter.filedialog
import os
import io
import qrcode
import win32clipboard
from datetime import datetime

# Choose save folder by filedialog
def save_folder():
    fTyp = [("", "*")]
    iDir = os.path.abspath(os.path.dirname(__file__))
    folder_name = tkinter.filedialog.askdirectory(initialdir=iDir)
    return folder_name

def generate_qr_code(url):
    # Generate QR code
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    # Add URL to QR code
    qr.add_data(url)
    qr.make(fit=True)
    # Generate QR code image
    img = qr.make_image(fill_color="black", back_color="white")
    return img

def save_to_clipboard(img):
    # Save QR code image to clipboard using win32clipboard
    temp_file_path = "temp_qr.png"
    img.save(temp_file_path)  # Save temporarily
    output = io.BytesIO()
    img.convert('RGB').save(output, 'BMP')
    data = output.getvalue()[14:]
    output.close()
    send_to_clipboard(win32clipboard.CF_DIB, data)
    os.remove(temp_file_path)
    print("QR code copied to clipboard!")

def send_to_clipboard(clip_type, data):
    # Clear the clipboard and set the data
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

def save_to_file(img, folder_name, filename):
    # Save QR code image to file
    if not filename:
        # Generate a filename based on the current date and time
        now = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"qr_{now}.png"
    # Check if the filename has an extension
    if not filename.endswith(".png"):
        filename += ".png"
    # Combine folder name with filename
    file_path = os.path.join(folder_name, filename)
    img.save(file_path)
    print(f"QR code saved as {file_path}")

# URL input
url = input("URL: ")
# Generate QR code
qr_img = generate_qr_code(url)
# Ask for save method
save_method = input("Save QR code to clipboard (c) or as a file (f)? ").lower()
if save_method == 'c':
    save_to_clipboard(qr_img)
elif save_method == 'f':
    folder_name = save_folder()
    if not folder_name:
        print("No folder selected. QR code will not be saved.")
    else:
        filename = input("Filename (press Enter to auto-generate): ")
        save_to_file(qr_img, folder_name, filename)
else:
    print("Invalid choice. QR code will be saved as a file.")
    folder_name = save_folder()
    if not folder_name:
        print("No folder selected. QR code will not be saved.")
    else:
        filename = input("Filename (press Enter to auto-generate): ")
        save_to_file(qr_img, folder_name, filename)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?