node中new ImageData 或 new Image未定义 UnhandledPromiseRejectionWarning: ReferenceError: ImageData is no

错误信息如下

(node:12834) UnhandledPromiseRejectionWarning: ReferenceError: ImageData is not defined
    at /Users/y/Desktop/exps/server.js:133:19
    at done (/Users/y/Desktop/exps/ebag.js:178:17)
    at /Users/y/Desktop/exps/ebag.js:277:13
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:12834) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

 

原因

node中不支持该函数使用

 

解决办法

在js浏览器端打印 new ImageData 可以看到结果如下(是初始化了像素点的整列)

 

我们可以自定义一个数组 进行处理

// 自定义像素整列空数组
let img = {
    data:[],
    height: 384,
    width: 384
}

 

Done

 

 

 

扩展参考

// 十进制图片信息
let result = <buffer>;

// 自定义像素整列空数组
let img = {
    data:[],
    height: 384,
    width: 384
}

// 计算buffer中对应每个像素点的RGB值
for (let i = 0, j = 0; i < result.length; i += 3, j += 4)
{
    img.data[j+0] = result[i+0]
    img.data[j+1] = result[i+1]
    img.data[j+2] = result[i+2]
    img.data[j+3] = 0xff
}
            
// 组合信息
let rawImageData = {
    data: img.data,
    width: 384,
    height: 384
}

// jpeg编码  需要 npm install jpeg-js (具体图片buffer为什么类型 就install && require对应的包)
let jpg_data = jpeg.encode(rawImageData, 50);

// jpeg编码后的图像数据 base64转码   需要 npm install base64-js
let jpg_data_base = base64.fromByteArray(jpg_data.data);

// 然后就可以以base64的方式渲染图片了

 

 

 

 

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页