从 Google 云存储读取图像并使用 Google 云功能发送

Read image from Google Cloud storage and send it using Google Cloud function

我想做以下事情: 创建一个 Google 云函数(http 触发),它只需从存储桶(Google 云存储)中读取图像文件并将其作为响应发送。

我尝试了一些组合,我认为它应该是这样的:

'use strict';
const gcs = require('@google-cloud/storage')();

exports.sendImage = function sendImage(req, res) {
    let bucket = gcs.bucket('my-bucket-name');
    let myImage = bucket.file('my-image-file.jpg');


    res.contentType('image/jpeg');
    res.end(myImage, 'binary');
};

上面的函数部署成功,但是当我仅使用 url(在浏览器上)触发它时,它没有显示任何结果。

我尽可能简单地做到这一点,因为如果它适用于一张图片,我可以改进代码以调用任何图片。

我的最终目标是制作类似于此 post 中显示的内容: https://medium.com/google-cloud/uploading-resizing-and-serving-images-with-google-cloud-platform-ca9631a2c556

但是 运行 在 Google 云功能上。如果我设法发送一个简单的图像,我可以使用一些模块,例如 node-image-resize 到最终结果。

好吧,我可以自己找到它,我认为它可以帮助很多其他人。所以请执行以下操作:

1 - 在 Google Cloud Storage 上创建一个存储桶,假设名称为 [my-bucket]

2 - 创建一个 Google Cloud Function,我们将其命名为 imageServer。

3 - 不要忘记编辑 package.json 文件。我的是这样的:

{
  "name": "image-server",
  "version": "0.0.1",
    "dependencies": {
    "@google-cloud/storage": "^1.2.1"
  }
}

4 - 发送简单图像的代码非常简单(在我弄明白之后):

'use strict';

const gcs = require('@google-cloud/storage')();

exports.imageServer = function imageSender(req, res) {
  let file = gcs.bucket('my-bucket').file('test-1.jpg');
  let readStream = file.createReadStream();

  res.setHeader("content-type", "image/jpeg");
  readStream.pipe(res);

};

Obs:测试图像是名为 [test-1.jpg] 的文件,它位于存储桶的根目录中。所以,从这里,我能够将它发送到浏览器。现在只需更改代码即可实现我在问题中所说的主要目标。

希望对您有所帮助。

参考链接: Google Cloud Storage NPM Google cloud Functions Hello World tutorial

谢谢,它非常有帮助,让我走上了正确的轨道。我想使用与 Google 云存储紧密集成的 Firebase 云函数从存储桶中获取文件,然后通过 https 提供它。

我还想先检查存储桶中的文件是否存在,如果不存在,则提供存储桶中的占位符图像。

经过一些谷歌搜索 which brought me to the file.exists() 方法示例后,我得到了这个:

第一个

const functions = require("firebase-functions");
const {initializeApp} = require("firebase-admin/app");
const {getStorage} = require("firebase-admin/storage");

然后

initializeApp({
  storageBucket: "my-bucket-name",
});

然后我导出了一个 returnPhoto 函数以通过 https

提供照片
exports.returnPhoto = functions.https.onRequest((req, res) => {
  let file = bucket.file("image_name.jpg");
  file.exists().then(function(data) {
    const exists = data[0];
    if (exists) {
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching the requested photo.");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    } else {
      file = bucket.file("notfound_image.jpg");
      file.createReadStream()
          .on("error", function() {
            console.log("Error while fetching notfound_image.jpg");
            res.end();
          })
          .pipe(res.setHeader("content-type", "image/jpeg"));
    }
  });
});