首页 > 解决方案 > 如何使用 javascript 获取“原始”图像数据?

问题描述

我有一个 png 图像的 base64 编码(字符串以 开头data:image/png;base64,)。我的理解是,这是用 png 编码的图像的 base64 表示。有没有办法使用nodejs逐像素地获取图像的“原始”像素?

标签: javascriptnode.js

解决方案


尝试这个。首先从字符串中删除“data:image/png;base64”。IE

const img = base64Data.replace(/^data:image\/png;base64,/, "");

然后从base64转换图像。

const imgBuf = Buffer.from(img, 'base64');

在这一点上,我们有二进制的图像。然后我们可以得到像素。试试这个模块https://github.com/scijs/get-pixels

const getPixels = require("get-pixels");

getPixels(imgBuf, "image/png", function(err, pixels) {
    if (err) {
        console.log("Bad image path")
        return
    }
    console.log("got pixels")
});

推荐阅读