【发布时间】:2020-08-16 09:38:19
【问题描述】:
我正在尝试使用 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,
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);
}
};
}
};
【问题讨论】:
-
对此有什么解决办法吗?谢谢!
标签: javascript node.js google-cloud-ml google-cloud-vision