Module – Share Your Image with QR code

Function

By using this module, you can upload your image to SM.MS and obtain a unique URL for downloading it. Subsequently, the URL is converted into a QR code, making it easily accessible for users to download the image using their smartphones.

Input: an image
Output: URL and QR code

Requirements

pip install opencv qrcode pillow requests

Code of the Module

import os.path
import pathlib
import requests
import cv2
import datetime
import random
import string
import numpy as np
import qrcode

## Register a New User via https://sm.ms/register
## Then, put your API_KEY below
API_KEY = "####"

def generate_qr_code(url):
    qr = qrcode.QRCode(version=1, box_size=10, border=4)
    qr.add_data(url)
    qr.make(fit=True)

    # 转为Opencv格式
    qr_image = qr.make_image(fill_color="black", back_color="white")
    qr_image_cv = cv2.cvtColor(np.array(qr_image.convert("RGB")), cv2.COLOR_RGB2BGR)
    print("二维码生成成功")
    return qr_image_cv

def generate_random_image(width=256, height=256):
    # 创建一个随机的彩色图像
    image = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
    return image

def generate_random_filename(extention=".jpg"):
    # 获取当前时间
    now = datetime.datetime.now()

    # 生成年月日时间的字符串
    timestamp = now.strftime("%Y%m%d%H%M%S")

    # 生成随机字符串作为文件名的后缀
    letters = string.ascii_lowercase
    random_suffix = ''.join(random.choice(letters) for _ in range(6))

    # 组合文件名
    filename = f"{timestamp}_{random_suffix}{extention}"  # 可根据需要更改文件扩展名

    return filename

def upload_image_to_smms(image, temp_savepath="temp_result"):
    # 生成随机文件名,存储到临时目录
    filename = generate_random_filename()
    pathlib.Path(temp_savepath).mkdir(parents=True, exist_ok=True)
    save_path = os.path.join(temp_savepath, filename)

    # 保存图像到本地
    cv2.imwrite(save_path, image)

    # 发送POST请求上传图像
    url = "https://sm.ms/api/v2/upload"
    headers = {'Authorization': API_KEY}
    files = {'smfile': open(save_path, 'rb')}
    response = requests.post(url, headers=headers, files=files)
    # 解析响应获取图像URL
    if response.status_code == 200:
        json_response = response.json()
        print(json_response)
        if json_response['code'] == 'success':
            return json_response['data']['url']
    else:
        raise ValueError(f"Upload file failed with response status_code: {response.status_code}")
    return None

def download_image_from_smms(image_url, temp_savepath="temp_result_output"):
    # 生成随机文件名,存储到临时目录
    filename = generate_random_filename()
    pathlib.Path(temp_savepath).mkdir(parents=True, exist_ok=True)
    save_path = os.path.join(temp_savepath, filename)

    response = requests.get(image_url)
    if response.status_code == 200:
        with open(save_path, 'wb') as file:
            file.write(response.content)
        print(f"图像下载成功, 保存到 {os.path.abspath(save_path)}")
    else:
        print("图像下载失败")
    return

if __name__ == '__main__':
    # 生成随机图片
    cv2_img = generate_random_image(width=256, height=256)

    # 上传到图床
    url = upload_image_to_smms(cv2_img)
    print(url)

    # 从URL下载图片
    download_image_from_smms(url)

    # 把URL转换成 QR code
    cv2_img = generate_qr_code(url)
    cv2.imshow("QR", cv2_img)
    cv2.waitKey(0)

Usage

Run the code, and you will generate a random image and see the QR code to download it.

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇