首页 > 解决方案 > 节点JS | 谷歌视觉 API | 将 base64 发送到 Google Cloud Vision 时出现“错误的图像数据”

问题描述

我正在尝试使用 Google Cloud Vision API 并尝试从图像中提取颜色。当我尝试将裁剪的图像发送到 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);
      }
    };
  }
};

标签: javascriptnode.jsgoogle-cloud-mlgoogle-cloud-vision

解决方案


为此苦苦挣扎了一段时间。原来,删除data:image/png;base64, 排序的东西出来


推荐阅读