app.qrcode - 二维码 API
二维码生成与识别。
生成
app.qrcode.generate(text, opts?)
生成二维码图片。
参数:
text(string) - 要编码的文本opts(table):path(string, 必填) - 输出图片路径size(number, 可选) - 图片尺寸,默认 256correctionLevel(string, 可选) - 纠错级别:"L","M"(默认),"Q","H"color(string, 可选) - 前景色,"#RRGGBB"格式backgroundColor(string, 可选) - 背景色,"#RRGGBB"格式
返回值: boolean, error
-- 基础生成
app.qrcode.generate("https://example.com", {
path = "/tmp/qr.png"
})
-- 自定义样式
app.qrcode.generate("https://example.com", {
path = "/tmp/qr.png",
size = 512,
correctionLevel = "H",
color = "#1A1A2E",
backgroundColor = "#E0E0E0"
})
识别
app.qrcode.recognize(imagePath)
识别图片中的二维码。
参数:
imagePath(string) - 图片文件路径
返回值: array<table>, error - 每项包含:
text(string) - 解码的文本type(string) - 类型("QRCode")bounds(table) - 位置:{x, y, w, h}
local codes, err = app.qrcode.recognize("/path/to/image.png")
if codes then
for _, code in ipairs(codes) do
app.log.info("内容: " .. code.text)
end
end
app.qrcode.recognizeFromScreen(opts?)
截取屏幕并识别二维码。
参数:
opts(table, 可选):displayId(number) - 显示器 IDrect(table) - 截取区域:{x, y, w, h}
返回值: array<table>, error - 同 recognize()
local codes = app.qrcode.recognizeFromScreen()
if codes and #codes > 0 then
app.clipboard.setText(codes[1].text)
app.notification.show("二维码", "已复制: " .. codes[1].text)
end
示例
为选中文件生成二维码
function MyPlugin:handleGenerateQR(context)
local file = context.selectedFiles[1]
local text = app.dialog.input("输入内容", app.path.basename(file))
if not text then return end
local qrPath = app.path.removeExtension(file) .. "_qr.png"
local ok, err = app.qrcode.generate(text, {
path = qrPath,
size = 512,
correctionLevel = "H"
})
if ok then
app.notification.show("完成", "二维码已生成")
app.finder.reveal(qrPath)
else
app.dialog.alert("错误", err or "生成失败")
end
end
识别图片中的二维码
function MyPlugin:handleScanQR(context)
local file = context.selectedFiles[1]
local codes, err = app.qrcode.recognize(file)
if not codes then
app.dialog.alert("错误", err or "识别失败")
return
end
if #codes == 0 then
app.dialog.alert("结果", "未识别到二维码")
return
end
local text = codes[1].text
app.clipboard.setText(text)
app.notification.show("二维码", "已复制: " .. text)
end