V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ciming
V2EX  ›  Node.js

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

  •  
  •   ciming · 2021-07-14 14:58:48 +08:00 · 2037 次点击
    这是一个创建于 1007 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    7 条回复    2021-07-27 18:57:36 +08:00
    ysc3839
        1
    ysc3839  
       2021-07-14 15:03:45 +08:00
    用 Swift 写个命令行工具,然后 Node.js 调用吧。
    james2013
        2
    james2013  
       2021-07-14 15:32:28 +08:00
    如下是使用 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);
    }
    },
    ddsfeng
        3
    ddsfeng  
       2021-07-14 15:41:19 +08:00
    google 关键字 pngpaste
    JasonEWNL
        4
    JasonEWNL  
       2021-07-14 16:14:33 +08:00
    pbpaste 已经接近可用的思路了,可以参照下面的方案写个函数存在 .*shrc 里:

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

    cat path/to/file.png | openssl base64 | tr -d '\n' | pbcopy
    magicdawn
        5
    magicdawn  
       2021-07-27 18:44:40 +08:00
    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)
    magicdawn
        7
    magicdawn  
       2021-07-27 18:57:36 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5539 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 08:58 · PVG 16:58 · LAX 01:58 · JFK 04:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.