如何解决节点JS | Google Vision API |将base64发送到Google Cloud Vision时出现“不良图像数据”
我正在尝试使用Google Cloud Vision API,并尝试从图像中提取颜色。 当我尝试将裁剪的图像发送到Vision API并收到“错误的图像数据”错误消息时,就会出现问题。
-
我发送给Vision API的Base64提示正在起作用 当我将其发送给客户端并创建图像或画布时。
-
通过请求发送到服务器的纯URL (req.headers.imageurl)发送到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,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);
}
};
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。