javascript - 节点JS | 谷歌视觉 API | 将 base64 发送到 Google Cloud Vision 时出现“错误的图像数据”
问题描述
我正在尝试使用 Google Cloud Vision API 并尝试从图像中提取颜色。当我尝试将裁剪的图像发送到 Vision API 并收到“错误的图像数据”错误消息时,就会出现问题。
我发送给 Vision API 的 Base64 在我将它发送到客户端并创建图像或画布时得到错误正在工作。
通过请求 (req.headers.imageurl) 发送到服务器的纯 URL 在发送到 Vision API 时有效。
从服务器从 base64 创建的图像在下载并上传到https://cloud.google.com/vision的“测试 api”时功能齐全
会不会有一些 CrossOrigin 问题?但是后来我不明白为什么我不能在稍后将它发送到客户端时将其绘制到画布上。
在此先感谢您的帮助!
从裁剪图像中请求和发送 Vision API 请求的函数
// Imports the Google Cloud client library
const vision = require("@google-cloud/vision");
const client = new vision.ImageAnnotatorClient();
const fetch = require("../functions/Fetch");
const imageEdit = require("../functions/ImageEdit");
exports.colorDetection = async (req, res) => {
// Then you 'get' your image like so:
await fetch.getImage(req.headers.imageurl, async function (err, data) {
// Handle the error if there was an error getting the image.
if (err) {
throw new Error(err);
}
// Crop Image
const cropSettings = JSON.parse(req.headers.cropsettings);
const croppedImage = await imageEdit.CropImage(data, cropSettings);
const stringify = JSON.stringify(croppedImage);
const request = {
image: {
content: Buffer.from(croppedImage).toString("base64"),
},
};
// // Performs label detection on the image file
const [result] = await client.imageProperties(request);
console.log(result)
const colors = result.imagePropertiesAnnotation;
// const stringify = JSON.stringify(colors);
await res.json(stringify);
});
};
裁剪图像功能
const { createCanvas, Image } = require("canvas");
exports.CropImage = (data, cropSettings) => {
"user strict";
// Settings
let cropLeft = cropSettings.startX,
cropTop = cropSettings.startY,
cropWidth = cropSettings.width,
cropHeight = cropSettings.height;
// Canvas
let resize_canvas = createCanvas(cropWidth / 2, cropHeight / 2);
//Image
let crop_img = new Image();
crop_img.src = `data:image/png;base64,${data.toString("base64")}`;
function Crop() {
const ctx = resize_canvas.getContext("2d");
ctx.drawImage(
crop_img,
cropLeft,
cropTop,
cropWidth * 2,
cropHeight * 2,
0,
0,
cropWidth,
cropHeight
);
}
if (crop_img && crop_img.complete) {
Crop();
try {
const base64Img = resize_canvas.toDataURL("image/png", 1.0);
return base64Img
} catch (e) {
console.log(e);
}
} else {
crop_img.onload = function () {
Crop();
try {
const base64Img = resize_canvas.toDataURL("image/png", 1.0);
return base64Img
} catch (e) {
console.log(e);
}
};
}
};
解决方案
为此苦苦挣扎了一段时间。原来,删除data:image/png;base64,
排序的东西出来
推荐阅读
- entity-framework-core - 使用 Entity Framework Core 存储密码的最佳方式是什么?
- javascript - Odoo 14 更改 Javascript 中的输入值
- typescript - 如何使用 TypeScript 类型系统检查字符串是否全部为小写/大写?(不是运行时检查)
- keras - 高估和低估的自定义指标 MAE
- c# - EF Core:发生错误 - “实体 ID 更改后无法翻译 LINQ 表达式”
- mongodb - 手动增加 MongoDB BsonTimestamp 以恢复 ChangeStream 是否安全?
- marklogic - XDMP-ELEMRIDXNOTFOUND: cts:element-values -- MarkLogic 10 [marklogic] 中没有元素范围索引
- reactjs - 组件没有更新,我真的不明白为什么
- javascript - 如何将项目或目录的所有文件中的所有cjs文件重构为es6模块?(vscode)
- multithreading - 发件箱图案弹簧卡夫卡