如何将POST请求中的图片通过Cloud Function发送至Vision API
Hey there! Let's figure out how to make your Cloud Function handle POSTed images, send them to the Vision API, and send the results back to whoever made the request. Here's a clear, step-by-step approach with working code:
第一步:解析POST请求中的图片
Most of the time, images come in via multipart/form-data (like form uploads) or as a base64-encoded string in a JSON body. We'll cover both scenarios, starting with the common form upload case.
For multipart requests, we'll use busboy—a lightweight parser that works great in Cloud Functions.
第二步:调用Vision API并返回响应
Once we have the image as a Buffer, we can pass it directly to the Vision API's detection methods (we'll use text detection like your example, but you can swap it for label detection, face detection, etc.).
Full Working Code (Multipart/Form-Data)
const vision = require("@google-cloud/vision"); const Busboy = require("busboy"); // Initialize the Vision API client const client = new vision.ImageAnnotatorClient(); exports.processImage = (req, res) => { // Reject non-POST requests if (req.method !== "POST") { return res.status(405).send("Method Not Allowed"); } const busboy = new Busboy({ headers: req.headers }); let imageBuffer = null; req.startTime = new Date(); // Capture the uploaded file busboy.on("file", (fieldname, file) => { const chunks = []; file.on("data", (chunk) => chunks.push(chunk)); file.on("end", () => { imageBuffer = Buffer.concat(chunks); }); }); // Once all request parts are processed busboy.on("finish", async () => { if (!imageBuffer) { return res.status(400).send("No image file was provided"); } try { // Call Vision API's text detection (replace with your desired method) const results = await client.textDetection(imageBuffer); const textAnnotations = results[0].textAnnotations; // Send the Vision API response back to the caller res.status(200).json({ textAnnotations, processingTimeMs: new Date() - req.startTime }); } catch (err) { console.error("Vision API Error:", err); res.status(500).send("Failed to process the image with Vision API"); } }); // Pipe the request body to Busboy for parsing req.pipe(busboy); };
Key Notes for This Setup:
- Add Dependencies: You'll need to include
busboyin yourpackage.jsonsince it's not bundled with Cloud Functions by default:{ "dependencies": { "@google-cloud/vision": "^4.0.0", "busboy": "^1.6.0" } } - Permissions: Make sure your Cloud Function's service account has the
roles/vision.userrole (or the more granularcloudvision.images.annotatepermission) to call the Vision API.
Handling Base64-Encoded Images (JSON Body)
If your request sends the image as a base64 string in a JSON body (e.g., {"image": "base64-string-here"}), use this simplified code instead:
const vision = require("@google-cloud/vision"); const client = new vision.ImageAnnotatorClient(); exports.processImage = async (req, res) => { if (req.method !== "POST") { return res.status(405).send("Method Not Allowed"); } try { const { image } = req.body; if (!image) { return res.status(400).send("No base64 image data provided"); } // Convert base64 string to a Buffer const imageBuffer = Buffer.from(image, "base64"); const results = await client.textDetection(imageBuffer); // Return the full Vision API response res.status(200).json(results[0]); } catch (err) { console.error("Processing Error:", err); res.status(500).send("Failed to process the image"); } };
内容的提问来源于stack exchange,提问作者NodeBoyJS

