Mac 系统,Nodejs如何从剪切板中读取图片并转成base64

发布于 1周前 作者 yuanlaile 来自 nodejs/Nestjs

Mac 系统,Nodejs如何从剪切板中读取图片并转成base64

试了下 pbpaste命令,貌似只能打印出剪切板里的文本

8 回复

用 Swift 写个命令行工具,然后 Node.js 调用吧。


如下是使用 js 和 vue 从剪切板获取图片对象,实测可用.转成 base64 需要自己处理
getImage() {
const clipboardObj = navigator.clipboard;
if (clipboardObj !== undefined) {
setTimeout(async () => {
try {
const clipboardItems = await navigator.clipboard.read();
for (const clipboardItem of clipboardItems) {
// console.log(clipboardItem);
for (const type of clipboardItem.types) {
const blob = await clipboardItem.getType(type);
console.log(blob);
if(blob.type.includes(“image”)){
this.imageUrl = URL.createObjectURL(blob);

return
}else{
console.log(“not image”);
}

}
}
this.$message({
message: ‘剪切板没有图片’,
type: ‘warning’,
duration: 2000
});
} catch (err) {
console.error(err.name, err.message);
}
}, 100);
}
},

google 关键字 pngpaste

pbpaste 已经接近可用的思路了,可以参照下面的方案写个函数存在 .*shrc 里:

openssl base64 < path/to/file.png | tr -d ‘\n’ | pbcopy

cat path/to/file.png | openssl base64 | tr -d ‘\n’ | pbcopy

https://github.com/magicdawn/simple-mac-clipboard

和 Electron clipboard 差不多的 api, 之前做 electron, 碰到读图片导致 electron crash.
写了个 addon, 可以在 node or electron 中使用

const clip = require(‘simple-mac-clipboard’)
const buf = clip.readBuffer(‘public/png’) // png buffer
const base64 = buf.toString(‘base64’) // png buffer -> string (base64 encoding)

在Mac系统上,你可以使用Node.js从剪切板中读取图片并转换成Base64编码。这通常需要借助第三方库,比如clipboardy来读取剪切板内容,以及clipboard-image来专门处理图像。不过,clipboardy不支持直接读取图像,因此你可以使用clipboard库结合child_process模块来执行shell命令获取图像数据。

以下是一个示例代码,使用clipboard库和child_process来读取剪切板中的图片并转换成Base64:

# 首先,安装必要的库
npm install clipboard
const clipboard = require('clipboard');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

// 假设你已经将剪切板中的图片保存为临时文件
const tempImagePath = path.join(__dirname, 'temp_image.png');

exec(`pbpaste -Prefer png > ${tempImagePath}`, (err, stdout, stderr) => {
    if (err) {
        console.error(`Error: ${err}`);
        return;
    }

    fs.readFile(tempImagePath, (err, data) => {
        if (err) {
            console.error(`Error: ${err}`);
            return;
        }
        const base64Image = data.toString('base64');
        console.log(base64Image);
    });
});

注意:

  1. 此代码使用pbpaste命令将剪切板内容作为PNG文件保存到临时文件。
  2. 读取临时文件并将其转换为Base64编码。
  3. 需要在Mac终端环境中运行,并且需要确保pbpaste命令可用。

注意,这种方法依赖于系统命令,可能在非Mac系统上不可用。

回到顶部